The race is on!

June 30, 2008

The Podder Skinning Competition deadline is quickly drawing near.  As of 12:00 AM GMT on Tuesday, July 1, 2008 your opportunity to submit a Podder skin will be over.  The first submission has already be made, by Rudi Grobler (based on the work of Jose Fajardo).  I am very excited to see what else is submitted.  Stay tuned…


DataContextSpy

June 26, 2008

I just blogged about my new DataContextSpy class, over on my other blog. It uses Hillberg’s Freezable trick to gain access to an inheritance context from an object that is not in a logical tree. DataContextSpy is very simple, so it should be reusable in many scenarios.

I hope eventually Microsoft provides a first-class addition to WPF that makes it easy to create an artificial inheritance context. Having to rely on that strange aspect of Freezable is kinda…

LAME!

…though it’s great to have in the toolbox. ;)


Persisting field widths in XamDataGrid

June 20, 2008

I have been writing a lot about XamDataGrid on my other blog recently.  My most recent post shows how to save and load the widths of columns/fields across runs of the application.  This is just a temporary solution that will eventually be replaced by built-in functionality in the control, but until then, at least we now have a way to do this with ease.  My implementation even supports saving/loading the width of fields when showing hierarchical data (i.e. multiple related tables in the same grid).  Enjoy!


Allowing CommandManager to query your ICommand objects

June 17, 2008

One of the great parts about commands in WPF is that they know if they can currently execute or not. When they cannot execute, the control(s) that are set to execute the command will be disabled automatically. For example, if your application has no changed data, the Save toolbar button will automatically be disabled, assuming its Command property is set to the Save command.

WPF will automatically ask all of the commands being used in your UI if they can execute. This happens at various times, such as when input focus shifts to another control, an item is selected in a list, etc. You can also programmatically trigger this to happen by calling the CommandManager’s InvalidateRequerySuggested static method. This all seems magical, dreamy, and almost too good to be true.

Here’s the hitch: this beautiful system of commands automatically notifying the UI that they cannot execute only works out-of-the-box for RoutedCommands. If you simply implement ICommand and hook up, say, a Button’s Command property to reference that non-routed command, suddenly the Magical Love Machine comes to a grinding and screeching halt. Why? Because by default WPF has no idea that your custom ICommand objects exist. How would it?

Fortunately there is an easy solution to this problem. In your ICommand implementation, you make the CanExecuteChanged event hook the CommandManager’s RequerySuggested event. I lifted this little trick straight from Reflector, as I perused the RoutedCommand class…

class MyCommand : ICommand
{
public bool CanExecute(object parameter)
{
return maybeTrueOrFalse;
}

public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}

public void Execute(object parameter)
{
// Do something awesome.
}
}


Post about unbound fields in XamDataGrid

June 16, 2008

If you use the Infragistics XamDataGrid, you might want to check out my latest post about it.  I put together a demo app that shows the proper way to embed controls into unbound fields, and react to the user interacting with them.  Here’s the obligatory screenshot…


Understanding Templates in WPF

June 15, 2008

If you are versed in the ways of Windows Forms and plan on using WPF, brace yourself. The platform might seem somewhat similar at first glance. After that brief initial survey, the landscape changes dramatically. In my opinion, the primary differentiator is the fact that WPF makes heavy of use of something that does not even enter the mental landscape of WinForms. I am talking about templates.

As I explained in the fourth entry of my guided tour of WPF, templates are like a cookie-cutter. Instead of resulting in delicious baked goods, these cookie-cutters produce a tree of visual elements that can render something. What can they render? Anything.

Coming from a background in ASP.NET this concept might seem entirely natural, since the ASP.NET platform has used templates for years. The Repeater control, for example, makes heavy use of templates. The WPF ItemsControl is the moral equivalent of Repeater, in that it produces a static list of items based on a description of visual elements declared in markup.

In WPF there are several types of templates that you use often. They all derive from the abstract FrameworkTemplate class. DataTemplate is used to create a visualization of a non-visual object, such as a business object. ControlTemplate supplies a visual representation of a UI control, such as a Button or ListView. ItemsControl, and all of its subclasses (such as ListBox), create the layout panel that hosts their child elements via an ItemsPanelTemplate. Another commonly used template in WPF is the HierarchicalDataTemplate, which is a data template that has knowledge of how to display a data object’s child objects, such as in a master-detail situation.

The mental shift that I had to make, when leaving WinForms and entering WPF, is that a UI is made of templates. Forget about building a UI and then shoving data into it. That’s not the WPF way. In WPF we show data in a user interface, instead of showing a user interface that contains data. It is a subtle, yet crucial, distinction. If you find yourself creating a UI in WPF and then filling it with data, you are not doing things the WPF way. If you find yourself seeing the UI as a mere “outfit” that data “wears” then you are on the right track. At least, that’s my opinion.


Conditionally adding elements declared in XAML to the element tree

June 12, 2008

In my previous post I showed a markup extension that only creates elements declared in your XAML file if you are running with Full Trust from the CLR. After I posted that, Laurent Bugnion, a fellow WPF MVP and WPF Disciple (as well as a really great guy!), asked if I know of a way to use a markup extension to perform the moral equivalent of a #if … #elif … #endif in C#. That was an interesting question, so I decided to investigate. It turned out to be very simple.

Here is my new If class:

You can use that markup extension to conditionally add elements to the element tree, based on whether you are building a DEBUG or RELEASE build. Here is a demo of that class being used:

If you create a DEBUG build, the top TextBlock appears in the Window, otherwise the bottom TextBlock shows up. Naturally, if you have a more complicated set of build options, you can enhance my If class to take those build configurations into account.

[EDIT]

After I posted this, Andrew Smith pointed out that there is another way to achieve this, as seen here.  The approach involves the use of the Markup Compatibility XML namespace, and another assembly to contain your own XML namespaces.  That technique is more complicated to set up, but the elements in excluded blocks will not be created/seen by the XAML reader.

[/EDIT]

Download the source code here. NOTE: Change the file extension from .DOC to .ZIP and then decompress it.


Writing XAML that gracefully degrades in partial trust scenarios

June 12, 2008

Developing WPF applications that run with full trust allows you to remain blissfully unaware of the problems involved with working in a partial trust environment. Once you begin to take the limitations of running in partial trust into account, life becomes more complicated (and more full of headaches). This blog post shows a utility class I made, called IfFullTrustExtension, which helps to create XAML files that work well in both trust environments.

Recently at work, I inherited an application that runs both as full trust and as partial trust. It runs under full trust when deployed as a desktop application, and partial trust when deployed as an XBAP. The Visual Designer I was working with made some excellent looking UI assets in Blend, but they were causing problems when running in the XBAP because they made use of bitmap effects. Bitmap effects have a history of not working in partial trust because they rely on unmanaged code and, thus, require UIPermissions to be instantiated. I really liked how those effects made the Designer’s UI assets look, but didn’t want to get into the messy business of applying those bitmap effects in code.

I needed a way to conditionally apply bitmap effects to elements in XAML. I slept on it, and when I woke up this morning, I had the following solution in mind…

The real problem here is that you cannot instantiate a bitmap effect class if you are running in partial trust. Since XAML has no inherent concept of “trust,” I needed to introduce it. I also needed to provide a way to conditionally instantiate objects declared in XAML, based on the level of trust given to the app by the CLR. This resulted in my new IfFullTrust markup extension, as seen below:

Using the markup extension in XAML looks like this:

Note that the DropShadowBitmapEffect XAML is in a CDATA block, and the default XML namespace is mapped to the standard WPF default namespace. Since the XAML is in a CDATA block, the bitmap effect will not be instantiated when the Page loads, but the XML it contains will remain intact so that my markup extension can read it.

If you run this XBAP project with full trust, it looks like this:

Notice that the drop shadow appears, as expected. The screenshot below shows how to make the XBAP run in partial trust, which is the default (and recommended) configuration for an XBAP:

If you run the app now, no exception is thrown and the app runs just fine. But, as seen below, there is no drop shadow:

[EDIT]

After posting this, I found that Andrew Smith had already blogged another, though different, use of markup extensions to work with bitmap effects.  His technique is described here.  My markup extension is not specific to working with bitmap effects, but his has the advantage of having the XAML be verified by the compiler.

[/EDIT]

Download the source code here. NOTE: Be sure to change the file extension from .DOC to .ZIP and then decompress it.


Three tips for working with XBAP

June 10, 2008

There is not much documentation out there that explains the best ways to work with Xaml Browser Applications (XBAPs). At my job, I recently inherited an application that is deployed both to the desktop and as XBAP, so I decided to study up on the topic. To my dismay, there is hardly anything out there beyond the basics. I intend on helping to fill that gap by blogging about XBAP-related tips and tricks that I learn along the way.

In this post, I share three tips that have helped me out a lot already.

XBAP Tip 1

When in doubt, clear it out. The XBAP applications are stored in a local cache on the client. Sometimes this is great, sometimes it can be a problem. If you make some changes in your code/XAML that you just know should be appearing when you run the app, but don’t, then it’s time to clean your cache. You can do so by running this:

rundll32 %windir%\system32\dfshim.dll CleanOnlineAppCache

I put that command in the Run dialog and just run it whenever I feel that the XBAP Gods are not smiling down upon me.

XBAP Tip 2

Unfortunately Snoop does not work with XBAPs. But…Mole does!! In order to molenate an XBAP you need to perform one extra step, that is not necessary for a normal WPF app. If you try to open the Mole debugger visualizer for an XBAP with the default security settings, you will receive this error from Visual Studio:

In case that image does not show up for you, it says: “The application you are debugging has insufficient privileges to allow the use of custom visualizers. Please see the documentation for the list of required privileges.”

In order to give an XBAP sufficient privileges to be molenated, you must open the project’s properties, go to the Security tab, and select the “This is a full trust application” option. This is seen below:

XBAP Tip 3

This tip is related to tip 2. Since you probably do not want to deploy your XBAP as a full trust application, you need to remember to revert the project setting back to “This is a partial trust application” at some point. If you want to be 100% certain that you’ve done so, simply call the following method from your main Page’s constructor (or wherever makes sense for you):

void VerifyPartialTrust()
{
  try
  {
    new DropShadowBitmapEffect();
    Trace.Fail("Warning: Project set to Full Trust!");
  }
  catch
  {
  }
}

Since a partial trust XBAP cannot touch bitmap effects, such as DropShadowBitmapEffect, creating an instance of one will throw an exception. If you can create an instance without an exception being thrown, the code above shows a warning message that you can’t miss!


Yet another workaround for not having an inheritance context

June 5, 2008

There are several workarounds for the fact that you can’t give any arbitrary object an inheritance context (i.e. data bind the properties of any object to stuff in the WPF element tree), such as my virtual branch technique, and Hillberg’s Freezable approach. I recently came up with yet another, not-so-elegant, approach that I like to call GHETTO-INJECTION.


Follow

Get every new post delivered to your Inbox.

Join 285 other followers