Welcome!

Blog Feed Post

Understanding WPF and the XAML editor in PB12.NET (part III)

If you’ve been following this series, you’ve seen how easy it is (perhaps I should say, “will be”, since PB12 is still in beta…) to use the new features of PowerBuilder.NET. I hope I’ve been able to demystify any uncertainty you’re feeling about the upcoming transition to Windows Presentation Foundation (WPF) and Extensible Application Markup Language (XAML).

In this third (and final?) chapter of the series, we’ll add the final four commandbuttons, flesh out the PowerScipt, then add some custom XAML tags to the presentation layer which will really add some sizzle to the finished Calculator application. The point of this exercise is to show how XAML and WPF allows you to separate the user interface design/implementation from the “business logic” code of a PB.Net application.

 

To refresh everyone’s memory, this series is implementing the sample Calculator application from MSDN, which can be downloaded here. If you’ve gotten this far, we have the basic interface designed, using a GridPanel and some rectangular WPF commandbuttons. Not quite the same look and feel as the MSDN sample, which uses rounded commandbuttons, with cool animations for the MouseOver! and Clicked! events.

Here’s a screen shot of the MSDN sample app in action (which you wouldn’t see unless you have Visual Studio installed):

Sample WPF Calculator from MSDN

 

OK, so that app has some cool extra functionality, like a MultiLineEdit that simulates a running “paper trail” of the calculation history, some extra function keys, and Memory, so a direct “line for line” comparison to our PB.Net version won’t be a decent metric of application size. It’s not even an exercise on how to program a calculator or a Finite State Machine in PowerBuilder. This is really an attempt to show that PB.Net will be able to do everything that the Visual Studio developers can do with XAML and WPF, and more…

Back to the PB application: I’m not going to bloat this posting with the gory details of every event and method call. If you want to peruse the code, you can download the .Zip file containing the finished application here. But I will cover the XAML concept of Styles and Templates, which allow the PB developer to customize and extend the default GUI behavior. How about some rounded CommandButtons with a gradient background, and some animation to top it all off??

 

Step 1: Add the final four CommandButtons (BKSP, CE, C, and Enter)

The buttons we’ve placed into the application so far have been standard visual userObjects, descended from the CommandButton class. This allowed us to write some PowerScript into the ancestor classes, which are inherited by each instance that was dropped onto the gridPanel. These final four commandbuttons will just be regular WPF commandbuttons, each with one line of PowerScript in their clicked! events.

Select CommandButton from the Toolbox palette, and drop one each in the second row of grid cells (technically, Grid.Row=”1″). Stretch them to fit, and set their Margin and TextSize properties to match the other buttons in the grid. Their text property, reading from left to right, should be “BKSP”, “CE”, “C”, and “Enter”, and their names should be set to something indicative of their purpose – I named mine “cb_bksp”, “cb_clearentry”, “cb_clearall”, and “cb_enter”.

Now go into the Script window for each of them, and add the following lines of PowerScript.

cb_bksp:
parent.wf_backspace()

cb_clearentry:
parent.wf_clearEntry()

cb_clearall:
parent.wf_clearAll()

cb_enter:

//if we have only one operand, just exit
if parent.ib_eraseDisplay then Return
parent.wf_calculateResult()
parent.ib_eraseDisplay = TRUE
parent.lastOper = e_operation.none!
 
We defined the window functions that are called by these event scripts in Part II of this series. One nice new feature of PB.Net is that your PowerScript doesn’t have to compile cleanly before it can be saved, so if you haven’t already defined those window functions, you can go back and add them later! (You just can’t do a Full Build until they exist…)

 

Step 2: Define the custom templates and static resources in the XAML

Custom templates are used to define a standard look and feel for an object with a <Style> tag. Once a standard Style is defined, it can just be referenced from your controls, and they’ll “inherit” that behavior. It’s very similar to the way HTML works with Cascading Style Sheet definitions. These go into a section of the XAML called Resources, which can be “bound” to any container or control, depending on the desired scope of that reference. Since everything in our sample exists within the outer GridPanel, my XAML will create them as Grid.Resources. This example will be demonstrating three changes to the GUI of the calculator.

  1. Using ellipses as buttons, instead of plain old rectangular commandbuttons;
  2. Adding a nice shaded gradient to the background of those ellipses;
  3. Adding an animation effect to the “MouseOver” and “Clicked” events using a StoryBoard tag;

I’ve cobbled together most of the actual XAML for this from the MSDN sample itself, and John Strano’s blog post on using Custom Templates with PB.Net. Let’s get started!

 

Position the cursor in the XAML pane, right after the opening <Grid> tag on line 2, and start typing the <Grid.Resources> tag. Everything we’re adding goes inside this tag. With the shell’s Intellisense feature, all you need is the following key sequence:

<GR (tab) .RES (tab) > then enter.

Now you have a full <Grid.Resources></Grid.Resources> tag with room to enter more stuff inside.

The first thing we’ll add in there is the Storyboard tag, which defines the animation effect, and binds it to the ellipse control (which we’ll add in a moment.) That code looks like the following, and you can just copy and paste right inside the <Grid.Resources> tag.

<Storyboard x:Key="playStoryboard">
  <DoubleAnimation From="46" To="36" Duration="0:0:0.25" RepeatBehavior="1x"
AutoReverse="True" Storyboard.TargetName="TB" Storyboard.TargetProperty="(Ellipse.Height)" />
  <DoubleAnimation From="74" To="64" Duration="0:0:0.25" RepeatBehavior="1x"
AutoReverse="True" Storyboard.TargetName="TB" Storyboard.TargetProperty="(Ellipse.Width)" />
</Storyboard>

In a nutshell, this creates a Storyboard named “playStoryboard”, which animates an Ellipse named “TB”. It will shrink both the height and width by 10 pixels for .25 seconds, then return them to their original values.

 

Next, we’ll create the Ellipse style with its gradient background, and the event triggers that link to the Storyboard animation. This looks like a scary bit of XAML, but it’s not all that difficult to understand. This goes right after the closing </Storyboard> tag.  Place the cursor there and hit Enter to get a blank line, then paste the following code: 

<Style x:Key="Btn" TargetType="{x:Type pbwpf:CommandButton}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type pbwpf:CommandButton}">
        <Grid Width="74" Height="46">
          <Ellipse x:Name="TB" Stroke="DarkBlue" StrokeThickness="2">
            <Ellipse.Fill>
              <RadialGradientBrush Center="0.3,0.2" RadiusX="0.5" RadiusY="0.5">
                <GradientStop Color="Azure" Offset="0.1" />
                <GradientStop Color="CornflowerBlue" Offset="1.1" />
              </RadialGradientBrush>
            </Ellipse.Fill>
          </Ellipse>
          <ContentPresenter Name="Content" HorizontalAlignment="Center" VerticalAlignment="Center" />
        </Grid>
        <ControlTemplate.Triggers>
          <Trigger Property="IsMouseOver" Value="true">
            <Setter TargetName="TB" Property="Ellipse.Fill" Value="Aquamarine" />
          </Trigger>
          <Trigger Property="IsPressed" Value="true">
            <Setter TargetName="TB" Property="Ellipse.Fill" Value="Blue" />
          </Trigger>
          <EventTrigger RoutedEvent="ButtonBase.Click">
            <EventTrigger.Actions>
              <BeginStoryboard Name="playStoryboard" Storyboard="{StaticResource playStoryboard}" />
            </EventTrigger.Actions>
          </EventTrigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

 

All this code does is define a Style named “Btn”. The style defines an Ellipse named “TB” with RadialGradient properties, within a single-celled GridPanel (because all WPF controls must exist within a container).  It then defines the event triggers for the MouseOver and Clicked events, and binds the clicked event to the Storyboard we defined earlier.  The TargetType attribute of the Style says that this Style can be linked to by any control that is a “pbwpf:CommandButton”.   Whew!

  

Step 3: Bind the CommandButton controls to the new Style resource.

The next step is to tell the CommandButtons to use the new Style.  That is done by simply adding the Style attribute to the CommandButton definitions in the XAML.  Go into each <pbwpf:CommandButton> tag in the XAML pane, and add the following attribute:

Style="{StaticResource Btn}"

You can copy that to the clipboard and just paste it anywhere inside each pbwpf:CommandButton definition.  Watch the Design Layout automatically change as each tag is altered!  Also, note that we haven’t written any PowerScript code in the Clicked or MouseMove events!  This should help illustrate the inherent separation of concerns between the XAML-based presentation layer and the PowerScript-based business logic layer. 

Here’s a screen shot of the final product! 

Finished Project

If you want to get the calculator actually calculating, you’ll need the PowerScript for the window functions, which can be downloaded from the full source code in this .Zip file

 

The Final Analysis

Since we didn’t implement all of the functionality of the original MSDN example, a true line-by-line comparison isn’t really meaningful.  But I’m going to tell you anyway.  ;)   My example in PowerBuilder.Net comes in at a svelte 94 lines of code, compared to 498 lines of C# in the MSDN sample.  I’m confident that, even if I took the time to implement the remaining functionality, I wouldn’t add 400 more lines of code…

Of course, this is Beta software, and I am seeing some Beta strangeness…  For example, the buttons inside the grid should resize themselves as the grid cells expand, and they’re not.  Also, the animation in the mouse click is not returning the buttons to their original dimensions…  At this point, I’m not sure if it’s my XAML or an issue inside PB.Net, but I’ll certainly follow up as newer builds become available.  Feel free to post any thoughts or comments…

 

Enjoy!

-Paul-

 

Oct 7, 2009

Follow-up:  I’ve solved the animation problem where the commandbuttons were returning to a circle instead of an ellipse.  If you move the Width and Height properties from the <Grid> tag to the <Ellipse> tag, you’ll see the correct behavior.  Here’s an excerpt of the revised XAML, so you can see what I’ve changed.

<ControlTemplate TargetType=”{x:Type pbwpf:CommandButton}”>
   
<Grid>
       
<Ellipse Width=”73″ Height=”46″ x:Name=”TB” Stroke=”DarkBlue” StrokeThickness=”2″>
 

 

And make sure the From and To properties in the <StoryBoard> tag are set correctly as well:

<Storyboard x:Key=”playStoryboard”>
   
<DoubleAnimation From=”46″ To=”36″ Duration=”0:0:0.25″ RepeatBehavior=”1x” AutoReverse=”True” Storyboard.TargetName=”TB” Storyboard.TargetProperty=”(Ellipse.Height)” />
   
<DoubleAnimation From=”73″ To=”63″ Duration=”0:0:0.25″ RepeatBehavior=”1x” AutoReverse=”True” Storyboard.TargetName=”TB” Storyboard.TargetProperty=”(Ellipse.Width)” />
</Storyboard>
 

 

-P-

Read the original blog entry...

More Stories By Paul Horan

Paul Horan is a Senior Solution Advisor and Mobility Architect at SAP, and works with the SAP Mobile Platform and SAP Mobile Secure product lines. Paul joined SAP as part of their acquisition of Sybase in June, 2010. Prior to that, Paul worked for Sybase as a technical pre-sales architect supporting PowerBuilder, PowerDesigner, and SQL Anywhere. Paul works out of SAP's Reston VA office. A 1984 graduate of Indiana University, Paul currently resides in Arlington VA.

Latest Stories
This is going to be a live demo on a production ready CICD pipeline which automate the deployment of application onto AWS ECS and Fargate. The same pipeline will automate deployment into various environment such as Test, UAT, and Prod. The pipeline will go through various stages such as source, build, test, approval, UAT stage, Prod stage. The demo will utilize only AWS services including AWS CodeCommit, Codebuild, code pipeline, Elastic container service (ECS), ECR, and Fargate.
SAP is the world leader in enterprise applications in terms of software and software-related service revenue. Based on market capitalization, we are the world's third largest independent software manufacturer. Harness the power of your data and accelerate trusted outcome-driven innovation by developing intelligent and live solutions for real-time decisions and actions on a single data copy. Support next-generation transactional and analytical processing with a broad set of advanced analytics - r...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Despite being the market leader, we recognized the need to transform and reinvent our business at Dynatrace, before someone else disrupted the market. Over the course of three years, we changed everything - our technology, our culture and our brand image. In this session we'll discuss how we navigated through our own innovator's dilemma, and share takeaways from our experience that you can apply to your own organization.
Nutanix has been named "Platinum Sponsor" of CloudEXPO | DevOpsSUMMIT | DXWorldEXPO New York, which will take place November 12-13, 2018 in New York City. Nutanix makes infrastructure invisible, elevating IT to focus on the applications and services that power their business. The Nutanix Enterprise Cloud Platform blends web-scale engineering and consumer-grade design to natively converge server, storage, virtualization and networking into a resilient, software-defined solution with rich machine ...
Intel is an American multinational corporation and technology company headquartered in Santa Clara, California, in the Silicon Valley. It is the world's second largest and second highest valued semiconductor chip maker based on revenue after being overtaken by Samsung, and is the inventor of the x86 series of microprocessors, the processors found in most personal computers (PCs). Intel supplies processors for computer system manufacturers such as Apple, Lenovo, HP, and Dell. Intel also manufactu...
Digital transformation is about embracing digital technologies into a company's culture to better connect with its customers, automate processes, create better tools, enter new markets, etc. Such a transformation requires continuous orchestration across teams and an environment based on open collaboration and daily experiments. In his session at 21st Cloud Expo, Alex Casalboni, Technical (Cloud) Evangelist at Cloud Academy, explored and discussed the most urgent unsolved challenges to achieve fu...
Wasabi is the hot cloud storage company delivering low-cost, fast, and reliable cloud storage. Wasabi is 80% cheaper and 6x faster than Amazon S3, with 100% data immutability protection and no data egress fees. Created by Carbonite co-founders and cloud storage pioneers David Friend and Jeff Flowers, Wasabi is on a mission to commoditize the storage industry. Wasabi is a privately held company based in Boston, MA. Follow and connect with Wasabi on Twitter, Facebook, Instagram and the Wasabi blog...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
The dream is universal: heuristic driven, global business operations without interruption so that nobody has to wake up at 4am to solve a problem. Building upon Nutanix Acropolis software defined storage, virtualization, and networking platform, Mark will demonstrate business lifecycle automation with freedom of choice and consumption models. Hybrid cloud applications and operations are controllable by the Nutanix Prism control plane with Calm automation, which can weave together the following: ...
Inzata is a powerful, revolutionary data analytics platform for integrating, exploring, and analyzing data of any kind, from any source, at massive scale. Powerful AI-assisted Modeling and a patented analytics engine help users quickly load, blend and model raw and unstructured data into powerful enterprise data models, actionable real-time analytics and engaging visualizations. Go beyond spreadsheets and slides and compose a powerful narrative about how your business is performing, and how y...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO Silicon Valley 2019 will cover all of these tools, with the most comprehensive program and with 222 rockstar speakers throughout our industry presenting 22 Keynotes and General Sessions, 250 Breakout Sessions along 10 Tracks, as well as our signature Power Panels. Our Expo Floor will bring together the leading global 200 companies throughout the world of Cloud Computing, DevOps, IoT, Smart Cities, FinTech, Digital Transformation, and all they entail. As ...
Lori MacVittie is a subject matter expert on emerging technology responsible for outbound evangelism across F5's entire product suite. MacVittie has extensive development and technical architecture experience in both high-tech and enterprise organizations, in addition to network and systems administration expertise. Prior to joining F5, MacVittie was an award-winning technology editor at Network Computing Magazine where she evaluated and tested application-focused technologies including app secu...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
Only Adobe gives everyone - from emerging artists to global brands - everything they need to design and deliver exceptional digital experiences. Adobe Systems Incorporated develops, markets, and supports computer software products and technologies. The Company's products allow users to express and use information across all print and electronic media. The Company's Digital Media segment provides tools and solutions that enable individuals, small and medium businesses and enterprises to cre...