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 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.


Article about visualizing a binary rule system

June 1, 2008

I just published a different kind of WPF article than I typically create.  This one is called “Visualizing a Binary Rule System with WPF” and discusses an interesting data visualization app I made over the weekend.  If you want to check it out, here’s the link:

http://www.codeproject.com/KB/WPF/BinaryRuleSystem.aspx

By the way, the Podder Skinning Competition deadline is July 1st 2008, just one month away!  8)


Yield to the power of yield

May 26, 2008

I must admit, I had never really become too comfortable with the C# ‘yield’ keyword until recently. I knew that it was introduced in C# 2.0 as a means of simplifying the creation of an enumerator. I also knew that the C# compiler interprets the code in a method that uses the yield keyword. A compiler-generated implementation of IEnumerator exists behind the scenes, which implements the logic to produce the enumerator you declared in C#. Beyond that vague understanding, I was not too familiar with it. It felt “odd” so I rarely used it.

In my ‘Simplifying the WPF TreeView by Using the ViewModel Pattern‘ article I have a demo program that lets the user search through the items in a TreeView. The search logic uses the yield keyword, as seen below:

(Click on the image to view the source code at full-size)

The article also has a demo program that lazy-loads each item’s children. That demo does not provide the ability to search. Shortly after publishing the article, two people asked how to have a lazy-loaded tree with search capabilities. Aside from the fact that performing a search that produces no matching items will force all of the items to be loaded; it is a reasonable question. I decided to implement a solution.

At the time, I misunderstood exactly how my search method used the ‘yield’ keyword. I was under the false assumption that it was executing the search logic to completion when the FindMatches method is called, and storing the results in a collection of some type. As we will see later, this is entirely untrue, but I, too, can be an idiot sometimes. :)

I took the load-on-demand sample and added in the ability to search the items. The UI looks like this:

Based on my misunderstanding of how a yield-based enumerator works, I thought it would have been bad to use it in this situation. Since I (incorrectly) thought that it walked down the entire data tree upon creation, performing a search with it would have forced the entire tree to be loaded into memory at once. So I thought that I had to create a custom search algorithm that would perform the search and only load as many items into memory as necessary to find the first matching item. After finding the first match, the next time I perform the search, it should only load as many items as necessary to find the next matching item. And so on, and so on…

I have plenty of experience building recursive algorithms that walk over trees, but I had never built one like this. Most recursive algorithms store their state on the callstack. Each time the recursive method is called, a new frame is pushed onto the callstack, and it keeps track of the local variable values for you. By ‘local variables’ I mean things like, the current item, the index of a for loop, the parent item to which we return after processing a sub-tree, etc.

That’s all well and good, until you need to create a recursive method that returns a value and, later on, needs to resume processing from where it left off last time it was invoked. This is exactly what I needed to build. I needed to create a recursive algorithm that stores its state in an external data structure, so that I can effectively save and load that state between executions. It was an exciting Sunday morning programming exercise, for sure!

The source code of the demo app is available at the bottom of this post. In it, you’ll find a TreeViewItemViewModelSearch.cs file. It contains all of the code involved with this implementation. That file contains a static class, TreeViewItemViewModelSearch, which contains just one public method:

The SearchResult class implements IEnumerable<TreeViewItemViewModel> and its GetEnumerator returns an instance of SearchEnumerator, which implements IEnumerator<TreeViewItemViewModel>. This search logic is invoked by the enumerator’s MoveNext method:

(Click on the image to view the source code at full size.)

The helper classes seen in that algorithm are listed below:

As it turns out, none of this is necessary at all! If you look in the TreeViewItemViewModel class, you will see how there are two implementations of the search functionality. One of them uses the very elaborate code we just saw, and the other, which works JUST AS WELL as my code, is a simple method with the ‘yield’ keyword. Click on the following image to see how both techniques are used:

As seen in the FindMatches_Yield method, all that I had to do was add in code that lazy-loads the child items before it searches them! The compiler-generated implementation of my search logic will be invoked every time the enumerator’s MoveNext is called, and it only searches for one item at a time. This is perfect for a load-on-demand scenario. If I had known about this earlier, I never would have bothered to write that custom search enumerator. But then again, it was a lot of fun and quite interesting to implement, so it’s all good!

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