Tech Punch

Entries categorized as ‘WPF’

WPF XAML Markup – How Do I Preserve Whitespace Characters?

November 11, 2008 · 1 Comment

An issue you’re likely to run into in XAML (WPF, XBAP, and SIlverlight applications) is the need to keep whitespace characters intact in your markup.  By default, XML collapses all whitespace, ignoring strings of spaces, tabs, and return characters inside an XML node, which it graciously converts to a single space.

If you want to include a series of spaces in your XML node markup, you can add a xml:space=”preserve” attrbute to your XML elements.  This attribute  is part of the XML standard.  If you turn it on, it preserves all whitespace appearing inside the XML node, including any hard return characters included inside the XML node.

<Button Name="btnSample" xml:space=preserve">Respects my      spaces
and carraige return</Button>
  del.icio.us it! digg it! reddit! technorati! yahoo!

Categories: .Net · C# · Silverlight · WPF

WPF / WF – What Is A Dependency Property?

September 25, 2008 · 4 Comments

A new type of property, called a dependency property, was added to the .Net Framework with the release of .Net 3.0.  Dependency properties are used in both Windows Presentation Foundation (WPF) and Workflow Foundations (WF).  They are very similar in both frameworks, but are used for different purposes.

Dependency properties provides the plumbing for property value resolution, change notification, data binding, styling, validation, etc. for properties exposed in Windows Presentation Foundation (WPF) UI elements and Workflow Foundations (WF) custom activities.  Each dependency property is registered with a central repository that handles the change event notifications for you. 

Key Point – The Value of Dependency Properties Are Resolved

The ultimate goal of a dependency property, like any property, is to manage state.  But unlike normal .Net properties, the local property value is not stored in an instance variable. 

Instead, dependency properties are registered with the dependency property framework, and the underlying property value is resolved – meaning the value is determined by the dependency property framework based on rules defined by the property registration.

How To Create A Dependency Property

All WPF UI elements and Workflow Activities are derived from a high-level base classes called DependencyObject, which provides the basic functionality required to implement dependency properties.

public class MySampleControl : Control
{
    // Step 1: Register the dependency property 
    public static readonly DependencyProperty SpecialBrushProperty =
            DependencyProperty.Register("SpecialBrush", typeof(Brush),
            typeof(MySampleControl));

    // Step 2: Provide set/get accessors for the property
    public Brush SpecialBrush
    {
        // IMPORTANT!!
        // -----------
        // Dependency property accessors should not include custom logic 
        // because the framework may call the base.GetValue() and 
        // SetValue() methods directly
        get { return (Brush)base.GetValue(SpecialBrushProperty); }
        set { base.SetValue(SpecialBrushProperty, value); }
    }
}

As show in the code, there are two steps involved in creating a dependency property:

  1. Create a static field to hold a DependencyProperty object
    • By convention, the field should be named with the normal property name, followed by a “Property” suffix
    • This field will not contain the value of the property.  It simply defines the property that is registered with the dependency system
    • This field should be defined as a public, static, read-only field
      • The property must be available at all times, possibly shared among classes
      • The field is defined with the read-only keyword, meaning it can only be set in the static constructor of the type.
    • The field must be instantiated with a call to the static DependencyPropert.Register() method, passing:
      • The name of the property
      • The type of the property 
      • The type of the class that owns the property

      • Optionally, metadata used to define how the property is treated by the WPF framework
        • Meta-data flags to specify how the property affects the layout of the element (AffectsMeasure, AffectsArrange, AffectsRender, etc.)
        • Callbacks for handling property value changes (PropertyChangedCallback)
        • Callbacks to define custom value logic (CoerceValueCallback) 
        • Callbacks to validate values (ValidateValueCallback)
      • Optionally, metadata used to define how the property is treated by the WF framework
        • Include DependencyPropertyOptions enumerated value to specify additional characteristics for the property (ReadOnly, MetaData, etc.)
  2. Create property accessors (get / set)
    • Call DependencyProperty.SetValue() and GetValue() methods to set local values
    • DependencyObject is a high-level framework base class for WPF UI elements and WF activities
    • DependencyObject exposes the GetValue() and SetValue() methods

Isn’t That A Lot of Code for a Property?

At first glance, yes, this looks like an extremely complicated way to declare a property.  OK, at second glance, it’s still pretty complex.  But once you understand the power of dependency properties provide, especially in the Windows Presentation Framework (WPF), they’ll become a welcome addition to your coding toolbox. 

The convention takes a little getting used to. But after you’ve created a few, it comes quite naturally.  Visual Studio also includes some snippets to help add dependency properties:

  • Insert Snippet > NetFX30 > Define a DependencyProperty
  • Insert Snippet > Other > Workflow > DependencyProperty > Property

Subtle Differences Between in WPF and WF

While WPF and WF both use a similar dependency property frameworks, they are not identical!!

WPF UI elements and WF activities derive from a base DependencyObject class, and use a DependencyProperty class to register properties and get/set property values.  Despite the shared names, they are not the same classes!!

  • DependencyObject and DependencyProperty classes used by WPF reside in the System.Windows namespace
  • DependencyObject and DependencyProperty classes used by WF reside in the System.Workflow.ComponentModel namespace

Though their usage and function are very similar, they are not directly related to one another.

How are Dependency Property Values Resolved?

Property values for dependency properties are resolved automatically by the framework according to the following order of precedence:

  1. Property system coercion
  2. Active animations or animations with a hold behavior (WPF)
  3. Local value
  4. TemplateParent template properties (WPF)
  5. Implicit style (WPF)
  6. Style triggers (WPF)
  7. Template triggers (WPF)
  8. Style setters (WPF)
  9. Default (theme) style (WPF)
  10. Inheritance
  11. Default value from dependency property metadata

Note that the local value is 3rd in the order of precedence.  This means that a property may have a value, even if a local value for the property has never been set.  Also, if a property does have a local value, it may be overridden by higher level precedence items like an animation or data binding.

When Should I Use Dependency Properties In WPF?

Dependency properties are one of the most important concepts within WPF.  In WPF, dependency properties are required to support:

  • Data Binding
  • Animation
  • Styling
  • Value expressions
  • Property invalidation
  • Per-type default values

In short, it makes sense to expose dependency properties any time you expose a property for a custom UI element or control. 

When Should I Use Dependency Properties In WF?

Dependency properties are not used as heavily in Workflow Foundations (WF) as they are in Windows Presentation Foundation (WPF) , but they are still an important part of the WF framework.  They are used primarily when developing custom workflow activities that expose properties to support the following scenarios:

  • Activity Binding
    • This is the most common use of dependency properties in WF
    • Allows activities to expose properties that can be used to bind state to another activity
    • For example, binding the input of one workflow activity to the output of another workflow activity
  • Attached Properties
    • Attached properties are used to create a parent activity that can manage the state of it’s child activities
    • For example, the Conditioned Activity Group can attach a When property to each child
  • Meta Properties
    • Meta properties are defined by including new PropertyMetadata(DependencyPropertyOptions.Metadata) in the DependencyProperty.Register() method call 
    • Meta properties are set at design time and cannot be changed at run-time

    • Meta properties exist to guarantee the integrity of an activity
    • For example, at runtime, you can’t change the InterfaceType of an CallExternalMethod activity because InterfaceType is a meta-property

Sources

  del.icio.us it!

digg it!

reddit!

technorati!

yahoo!

Categories: .Net · C# · Visual Studio · WPF · Workflow

WPF – Create Irregular (Non-Rectangular) Borderless Windows

September 19, 2008 · 2 Comments

With Windows Presentation Foundation (WPF), it’s easy to craft irregular, non-rectangular top-level windows without borders to create a unique splash screen or a gadget-style user interface:

  • Modify the Window Properties
    • Set AllowTransparency property to true.
    • Set WindowStyle to None to remove window chrome
    • Set Background to Transparent
  • Add support for moving and closing the window if needed
    • Use the Window’s DragMove() method to allow users to reposition the Window
    • Add a UI element to allow users to close the window
void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    // DragMove handles all the window placement automatically!
    this.DragMove();
}

  del.icio.us it!

digg it!

reddit!

technorati!

yahoo!

Categories: .Net · C# · WPF

XAML Soup – XBAP vs. Silverlight 1.0 vs. Silverlight 2.0

August 27, 2008 · 1 Comment

Microsoft offers several new technologies to provide Rich Internet Applications (RIAs) to end users using WPF technology.  Silverlight 2 gets the most press as Microsoft’s “Flash Killer”, but it’s good to understand how these technologies relate, and the differences between them.

  • WPF Browser Applications (XBAPs)
  • Silverlight 1.0 (formerly dubbed WPF/E, Released)
  • Silverlight 2.0 (formerly dubbed Silverlight 1.1, currently in Beta 2)

All 3 technologies allow you to build dynamic user interfaces for the browser using the Windows Presentaion Foundation (WPF) using a browser plug-in.  You can use XAML to build front end UI elements, including some way cool transitions, blends, and animation.  You use code-behind to code against the UI and to add functionality to wire up the controls and respond to events, similar to the way you would in ASP.Net.

The primary difference between the three technologies is:

  • Browser / OS support
  • .Net Framework suppport
  • Language support

XAML Advantages Over Flash

Because these technologies are XAML, the markup is XML content, not binary like Flash.  This is a subtle but MAJOR difference:

  • XAML pages are indexable by search engines today.
  • XAML is accessible via the Document Object Model. This means that the same techniques you use in AJAX to update a particular part of the tree can be used to update a particular portion of a Silverlight application.  Document.GetElementById just got a lot more powerful.
  • Most of the skills you’ve developed in using the .Net Framework and building WPF applications are transferable to Silverlight application development

XBAP vs. Silverlight

.NET 3.0 introduced the Windows Presentation Foundation (WPF) which allows developeres to create stunning user interfaces for desktop applications using managed code. If you still haven’t experienced the power of WPF check out the WPF applications here.

The first step toward bringing WPF to the web was XBAP – XAML Browser Application (XAML is eXtensible Application Markup Language). XBAPs allow you to run Rich Internet Applications that look and function like WPF desktop applications. These XBAPs run inside the Internet Explorer in a limited-trust sandbox to prevent applications from accessing resources on the local system.

A restriction on XBAPs is that they need .NET framework 3.0 or higher to be installed on the client machine to run, and they only run on Windows systems under IE.   If you’re not in a tightly controlled intranet environment where you can dictate IE on Windows with the 3.0 framework on every client, Silverlight is the way to go.

Silverlight 1.0

Silverlight (formerly dubbed WPF/E) extends the boundaries by removing the dependency on the .Net framework, and providing cross-platform, cross-browser support to WPF applications with a browser plug-in.  As of now, Silverlight supports a subset of XAML and .Net functionality.

Silverlight 1 provides a solid framework for building RIAs using XML Application Markup Language (XAML) and JavaScript. Using XAML elements available in version 1 along with some JavaScript code you can animate objects in creative ways, skew and resize objects and interact with data dynamically using AJAX technologies and Web Services.

Although Silverlight 1.0 is powerful, it is a 1.0 release, and it has some serious shortcomings. 

  • Very limited control set.  Aside from a few very basic controls (Canvas, TextBlock, MediaElement, and basic shape controls) no user input or data display controls were included in version 1.  Control layout was also much too difficult. 
  • No support for the .Net framework, C# or Visual Basic.  Code behinds mucst be coded in Javascript, which is a web developer skillset, which may not overlap with WPF developers and doesn’t integrate natively with the Visual Studio development and debugging experience. 
  • Limited support for browsers and operating systems.  It’s currently supported with plug-ins for IE and FireFox on Windows.  Additional plug-in’s for  popular browsers on Linux and Mac platforms are currently in the works from 3rd party vendors.

Make Way For Silverlight 2.0

Silverlight 2.0 recently RTM’d, and moves the framework ahead nicely, with major improvements over the 2.0 release, including:

  • Adds a pared-down version of the .Net Framework complete with a miniature CLR hosted by a browser plug-in
  • Provides many new controls that can be used to capture user input and display collections of items
  • Ability to write C# or VB.NET code that runs in the Internet Explorer, Firefox, and Safari browsers
  • Includes networking features that allow data from local and remote services to be integrated into applications

Getting Started

To get started, you should install Visual Studio 2008 and Silverlight Tools for Visual Studio.  For more information, see the Getting Started page on the Silverlight site.

Sources

Share This Post

del.icio.us it! digg it! reddit! technorati! yahoo!

 

Categories: ASP.Net · Silverlight · WPF