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 session will provide an introduction to Cloud driven quality and transformation and highlight the key features that comprise it. A perspective on the cloud transformation lifecycle, transformation levers, and transformation framework will be shared. At Cognizant, we have developed a transformation strategy to enable the migration of business critical workloads to cloud environments. The strategy encompasses a set of transformation levers across the cloud transformation lifecycle to enhance ...
Your job is mostly boring. Many of the IT operations tasks you perform on a day-to-day basis are repetitive and dull. Utilizing automation can improve your work life, automating away the drudgery and embracing the passion for technology that got you started in the first place. In this presentation, I'll talk about what automation is, and how to approach implementing it in the context of IT Operations. Ned will discuss keys to success in the long term and include practical real-world examples. Ge...
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
So the dumpster is on fire. Again. The site's down. Your boss's face is an ever-deepening purple. And you begin debating whether you should join the #incident channel or call an ambulance to deal with his impending stroke. Yes, we know this is a developer's fault. There's plenty of time for blame later. Postmortems have a macabre name because they were once intended to be Viking-like funerals for someone's job. But we're civilized now. Sort of. So we call them post-incident reviews. Fires are ne...
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...
CloudEXPO New York 2018, colocated with DevOpsSUMMIT and DXWorldEXPO New York 2018 will be held November 12-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI and Machine Learning to one location.
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of computational needs for many industries. Their solutions provide benefits across many environments, such as datacenter deployment, HPC, workstations, storage networks and standalone server installations. ICC has been in business for over 23 years and their phenomenal range of clients include multinational corporations, universities, and small busines...
This sixteen (16) hour course provides an introduction to DevOps, the cultural and professional movement that stresses communication, collaboration, integration and automation in order to improve the flow of work between software developers and IT operations professionals. Improved workflows will result in an improved ability to design, develop, deploy and operate software and services faster.
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
Authorization of web applications developed in the cloud is a fundamental problem for security, yet companies often build solutions from scratch, which is error prone and impedes time to market. This talk shows developers how they can (instead) build on-top of community-owned projects and frameworks for better security.Whether you build software for enterprises, mobile, or internal microservices, security is important. Standards like SAML, OIDC, and SPIFFE help you solve identity and authenticat...
The digital transformation is real! To adapt, IT professionals need to transform their own skillset to become more multi-dimensional by gaining both depth and breadth of a wide variety of knowledge and competencies. Historically, while IT has been built on a foundation of specialty (or "I" shaped) silos, the DevOps principle of "shifting left" is opening up opportunities for developers, operational staff, security and others to grow their skills portfolio, advance their careers and become "T"-sh...
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 ...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...