Fun with fonts

So I’ve been playing around with the RichTextBox for WPF and decided that it would be a great idea to add font selection to the code. Obviously, this being WPF, I didn’t want to just list the fonts out, I wanted to list the fonts out in exactly the way they’d be displayed. In other words, I want the font name to be written out using the font itself. By now it shouldn’t come as a surprise to you that this is extremely easy to do in WPF.

First of all, it’s really easy to get a list of the fonts. .NET provides a handy little class cunningly enough known as InstalledFontCollection, so we’ll wrap that up in a handy list ready for use:

 

using System;
using System.Collections.Generic;
using System.Drawing.Text;
using System.Drawing;

namespace FontManager
{
    public class InstalledFonts : List<FontFamily>
    {
        public InstalledFonts()
        {
            InstalledFontCollection fonts = new InstalledFontCollection();
            this.AddRange(fonts.Families);
        }
    }
}

This class just wraps up the installed font families into a handy dataprovider format. This is all about being nice and blend-friendly.

Next we want to define a usercontrol to display the fonts. Something to note about this control; we display the data in a virtualizing stack panel – if you don’t, you could end up waiting quite a while for the first display of the font.

<UserControl
    x:Class="FontManager.InstalledFontDisplay"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:drawing="clr-namespace:System.Drawing;assembly=System.Drawing"
    xmlns:m="clr-namespace:FontManager"
    xmlns:sys="clr-namespace:System.Collections.Generic;assembly=mscorlib"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <UserControl.Resources>
        <Style x:Key="FontStyle">
            <Setter Property="Control.FontFamily" Value="{Binding Name}" />
            <Setter Property="Control.FontSize" Value="16" />
        </Style>
        <DataTemplate x:Key="FontTemplate">
            <StackPanel VirtualizingStackPanel.IsVirtualizing="True">
                <TextBlock
                    Text="{Binding Name}"
                    ToolTip="{Binding Name}"
                    Style="{StaticResource FontStyle}" />
            </StackPanel>
        </DataTemplate>
        <ObjectDataProvider x:Key="FontProvider" ObjectType="{x:Type m:InstalledFonts}"/>
    </UserControl.Resources>
    <ComboBox
            VerticalAlignment="Top"
            ItemsSource="{Binding Source={StaticResource FontProvider}}"
            ItemTemplate="{StaticResource FontTemplate}" />

</UserControl>

That’s it – that’s all there is to displaying your font names in the appropriate font. It is so easy, and yet another reason to love WPF. Go on – you know you love it.

Binding to a single object.

So today, on CodeProject, one of the WPF regulars posed a question about whether or not you could only bind to ObservableCollection objects, and if you could bind to single objects, how could you guarantee two way databinding goodness. As you may well imagine, I promptly answered that you could indeed bind to a single object and implement two way databinding with it. The discussion also posed the question, could WPF bind to properties that linked into child objects and display these – from separate usercontrols.

This seemed to me to be an ideal candidate for demonstrating the beauty and wonder that is the WPF databinding infrastructure. If you’ve only ever been exposed to WinForms or ASP.NET databinding, then you are in for a major treat – WPF (and Silverlight) provide so much more bang for your buck with binding that it’s hard to see how we managed before. First of all, let’s take a look at our business object classes, Benefit and Customer. Both of these classes implement INotifyPropertyChanged so that we get access to the notification mechanism that supports two way binding.

First of all, here’s Benefit.cs:

Benefit.cs

And here’s Customer.cs:

Customer.cs

As you can see, there’s nothing out of the ordinary in these classes – they don’t do anything clever. They are just your bog standard, basic model classes.

Now, here’s the main window XAML:

Window1.xaml

The TextBoxes are bound to the relevant entries in the Customer class using the familiar {Binding Path=…} syntax. But wait, where’s the Benefit class in all this? I added it for a reason, yet there’s no sign of it. Well, as you can see – there’s a reference to a UserControl (BenefitsControl), and we are going to perform the actual binding in this class. Here’s the definition of BenefitsControl.xaml:

benefitscontrol.xaml

Look – there’s the binding Benefits.ProviderName, but would it surprise you to know that I’m not going to put the data class anywhere near this control. I’m going to set the DataContext on the parent control and let the usercontrol “find” the data there. Here’s the implementation of the code behind the parent XAML (Window1.cs):

window1.cs

So – here’s the application in all its glory:

runningapplication

Well – now that we’ve covered the code, how does the databinding actually work? How does the user control actually get its binding to work? This is where the wonder that is WPF actually comes into play. If the binding can’t find data in the data context at the current level, it works its way back up the logical tree until it can. Seriously – I love this stuff, and I’d hate to go back from it.

The code for this application can be downloaded here. Note that you’ll need to change the extension from .doc to .zip.

customerboundsamplezip

Action based ViewModel and Model validation.

A while ago, WPF guru Josh Smith blogged about using the ViewModel to provide a first line of defence when validating data using the MVVM model. In his article, Josh talks about having the ViewModel perform some validation before passing this back to the underlying model. In his example, he uses a string property to perform initial validation on a UI element before it updates an integer, so that the user can type in abc123, but the model only gets updated if it’s a valid number. Please read his article here for more information.

While I liked Josh’s implementation, there was something nagging at me – his implementation relied heavily on switch statements in the property validation, and this really goes against the grain for me. Thinking about this for a while, it seemed to me that we could achieve a similar implementation and, at the same time, provide a nice level of abstraction. To do this, we can use the Action<T> delegate to nicely decouple the validation from the actual property validation. The following class provides the underlying mechanism for separating the validation.

ModelBase class

Now, both the ViewModel and Model classes can derive from this class and get access to the same functionality. The following class demonstrates this:

Person class

The interesting bit of this class is how simple the implementation of IDataErrorInfo here actually is. All the “magic” has been taken care of by creating an Action that will invoke the ValidateAge method. By calling AddValidation on the base class and passing the name of the property that the validation applies to, we can automatically hook up to perform the validation.

You can download the sample project here. Be sure to change the extension back from Doc to Zip and then decompress it.

Watermarked TextBox

Well, I love mucking around in code and I recently decided to see how easy it would be to knock together a user control that would work in both WPF and Silverlight. If you keep it simple, it is really really easy to do. To this end, I present to you the WatermarkTextbox.

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace WaterBox
{
 
public class WatermarkTextBox : TextBox, INotifyPropertyChanged
 
{
   
public WatermarkTextBox()
    {
      ApplyWatermark();
    }

 

    protected virtual void Changed(string propertyName)
    {
      ApplyWatermark();
     
PropertyChangedEventHandler handler = PropertyChanged;
     
if (handler != null)
      {
        handler(
this, new PropertyChangedEventArgs(propertyName));
      }
    }

    private string _watermarkText = “Watermark”;
   
public string WatermarkText
    {
     
get
     
{
       
return _watermarkText;
      }
     
set
     
{
       
if (_watermarkText != value)
        {
         
if (string.IsNullOrEmpty(Text) || Text == _watermarkText)
          {
            Text =
value;
          }
          _watermarkText =
value;
          Changed(
“WatermarkText”

);
        }
      }
    } 
 

 

 

    private System.Windows.Media.Brush _watermarkForeground = new SolidColorBrush(Colors.LightGray);
   
public System.Windows.Media.Brush WatermarkForeground
    {
     
get
     
{
       
return _watermarkForeground;
      }
     
set
     
{
       
if (_watermarkForeground != value)
        {
          _watermarkForeground =
value;
          Changed(
“WatermarkForeground”

);
        }
      }
    } 
 

 

 

    private System.Windows.Media.Brush _watermarkBackground = new SolidColorBrush(Colors.Yellow);
   
public System.Windows.Media.Brush WatermarkBackground
    {
     
get
     
{
       
return _watermarkBackground;
      }
     
set
     
{
       
if (_watermarkBackground != value)
        {
          _watermarkBackground =
value;
         Changed(
“WatermarkBackground”

);
        }
      }
    } 
 

 

 

    private System.Windows.Media.Brush _standardForeground = new SolidColorBrush(Colors.Black);
   
public System.Windows.Media.Brush StandardForeground
    {
     
get
     
{
       
return _standardForeground;
      }
      set
     
{
       
if (_standardForeground != value)
        {
          _standardForeground =
value;
          Changed(
“StandardForeground”

);
        }
      }
    } 
 

 

 

    private System.Windows.Media.Brush _standardBackground = new SolidColorBrush(Colors.White);
   
public System.Windows.Media.Brush StandardBackground
    {
     
get
     
{
       
return _standardBackground;
      }
     
set
     
{
       
if (_standardBackground != value)
        {
          _standardBackground =
value;
          Changed(
“StandardBackground”);
        }
      }
   

} 
 

 

 

    private void 

SetStandard()
    {
      Foreground = StandardForeground;
      Background = StandardBackground;
    } 
 

 

 

    protected override void OnGotFocus(RoutedEventArgs  e)
    {
     
if (Text == WatermarkText)
      {
        Text =
string.Empty;
        SetStandard();
      }
     
base

.OnGotFocus(e);
    } 
 

 

 

    protected override void OnLostFocus(RoutedEventArgs e)
    {
      Text = Text.Trim();
     
if (Text.Length == 0)
      {
        ApplyWatermark();
      }
     
base

.OnLostFocus(e);
    } 
 

 

 

    private void ApplyWatermark()
    {
     
if (string.IsNullOrEmpty(Text) || Text == WatermarkText)
      {
        Text = WatermarkText;
        Foreground = WatermarkForeground;
        Background = WatermarkBackground;
      }
    }

    #region

 
INotifyPropertyChanged Members
   
public event PropertyChangedEventHandler PropertyChanged;
   
#endregion
 
}
}

 

Please feel free to use this class as you like. It comes with no warranty because it’s intended as a proof of concept only. It can do with a tidy up, and it should use Coerce values but I leave that for you to do.

Binding to enumerations

In previous blog posts, I’ve talked about how you can use XAML to bind to various items. Here, I’d like to show you how to simply bind to an enumeration. I love the fact that binding does so much for you without you having to do much at all.

First of all, we’ll look at the XAML, and then we’ll go over the code.

In the resources section, we create a data provider that calls the GetValues method on an enumeration. Obviously we need to identify the enumeration that we are interested in, so we supply the relevant enumeration in the MethodParameters.

Finally, it’s a simple case of binding to our object data source. You’ve gotta love WPF.

XAML binding goodness

If you’re wondering why you should make the move to WPF, I’d like to share a little sample that demonstrates just how powerful WPF databinding really is, and how you can use it to bind to things that aren’t as obvious. In this sample, we’re going to create a status bar that shows whether certain keys are enabled or not. These are the Insert, Scroll Lock, Num Lock and Caps Lock keys that have their status displayed in applications like Word.

In order to perform this “magic”, we need to use a bit of the Windows API to get the state of the keys we are interested in. We use the GetKeyState API call in user32.dll, with an enumeration mapping the values we’re interested in.

The trick to actually reacting to the changes lies in previewing the keyup event, which allows you to intercept events from the keyboard (without changing them), and update the status of the keys accordingly. As we expose the keyboard items we are interested in as properties, using Change notification

Now that we have the keymanager in place, physically performing the binding is childs play.

There – I hope I’ve whetted your appetite, and got you interested in exploring data binding in WPF.

The notification gotcha.

When your application uses DataBinding in WPF, it’s great how little you actually have to do to have full two-way databinding running, with multiple views watching the same data, and reacting based on data changes. This amazingly powerful feature is, to me, one of the key selling features of WPF and Silverlight; no longer do you have to write huge amounts of code in your Windows Forms or ASP.NET application to manage all the different views on the same data. The underlying platform takes care of it for you.

One of the key components in this “magic”, is the use of INotifyPropertyChanged, which is responsible for notifying the data consumers that properties have changed. In your property setter, all you need to do is call the PropertyChanged event, telling it which property has changed and off you go – support for two-way databinding. This means that the following code is a common site

On the surface, there doesn’t appear to be much wrong with it, but there is a flaw with this approach. What happens if your value doesn’t change, but the setter is called – this can happen if the user retypes a value that is already in the field for instance, WPF will trigger the setter even though nothing has changed, which results in the PropertyChanged event being raised, triggering rebinds. In a desktop application, this normally isn’t that significant, but it could be much more significant in a Silverlight app with heavy data binding. We know what the problem is, the Change method being called when nothing has changed, and the fix is easy. Check to see if the old value of the property differs from the new value, and call the Changed method only when they do. This simple change means that databindings only occur when something has actually changed.

Reusable transaction handling in WPF with IEditableCollectionView.

One of the banes of my life as a professional developer is handling grid editing where it can react intelligently to the user cancelling a change in the middle of an add or edit. Fortunately, if you know where to look, .NET can do a lot of the heavy lifting for you. With a little bit of IEditableObject goodness and a couple of helper classes, it’s now easy to add change handling to your WPF applications.

The attached project contains a library with two classes in it that you can use to do the work for you. The first class, EditableObject, manages the commit and rollback phases. The behaviour of this class is interesting, so I’d like to take a few minutes to go over it with you. The first thing to note is that it’s abstract, so your data classes inherit from it. When you start an add or edit operation, a copy of the current data class is created and the values are stored in the copy before the edit can progress. This gives us a copy to go back to without having to manually copy fields out. It uses reflection to do this, which can be a little bit slow on complex types, but when you’re dealing with reflecting on one object it’s not too bad and it was a compromise I was prepared to live with in return for the flexibility it provides.

Important note: As we’re using reflection here, I’m only serializing the fields of the current object so the hierarchy doesn’t get traversed. This means that your dataclasses must derive from EditableObject directly in order to get access to all the features of this wrapper.

EditableObject implements the INotifyPropertyChanged interface with a bit of a twist. In normal operations, you would raise the PropertyChanged event as soon as you changed the property, but we don’t want this to happen until we’ve committed the edit/add. This means we have to step outside the normal behaviour a little bit, and to do this I’ve changed the usual implementation of INotifyPropertyChanged so that it just records the properties that have changed – then it plays them back when the edit is committed. Obviously, if it’s rolled back then the notification doesn’t go ahead.

The second class, EditableCollectionHandler, encapsulates IEditableCollectionView which was introduced in .NET 3.5 SP 1. Basically, this is a view that supports adding, editing and removing items from a collection. The add and edit are transactional, so we can hook this up to EditableObject directly. It provides the following methods, Add, Edit, Remove, CommitChanges and CancelChanges as well as two properties; DefaultView and EditView.

In the sample, I’ve created a ListBox inside a grid. The grid contains two DataTemplates to be used with the ListBox, the default template used to display the data, and the EditTemplate, to be used when we are adding or editing a line of data.

When you set up the link from your WPF application to EditableCollectionHandler, you specify the object you want the collection view to work against, the container of the templates and the type of item you want to specify for editing the items when you are adding or editing. You also set up the name of the default template and the edit template (if you have one), and then you’re good to go.

Requirements:

  • Visual Studio 2008
  • .NET 3.5 SP 1

Downloads

Be sure to change the extension from doc to zip and then uncompress it.

editablecollectionzip

MoXAML 2.0 Released.

Well – it’s taken me quite a while, but I’ve finally finished the new version of MoXAML Power Toys. This has been quite an undertaking, and has been the most fun I’ve had coding in quite a while. Anyway, what’s new in MoXAML?

AppWizard

As I’ve already intimated, there’s a new AppWizard in MoXAML. This command allows you to add a status bar, toolbar and menu to your application.

Calling the AppWizard

The AppWizard brings up a dialog where you choose whether or not you want to see a toolbar, a menu or a statusbar. If you choose to add a toolbar or menu, you even get standard icons added into your project. The CommandBindings and App.Resources are set up for you, and the relevant user controls are added into your main window. The statusbar hooks up to the Caps Lock, Scroll Lock, Insert and Num Lock keys to reflect the state of them. It also adds in a date and time which updates every second. I love WPF.

The AppWizard in action
The AppWizard in action

Behind the scenes, some of the code injected into your application is C#, but being a nice chap I’ve added a converter in there which translates the C# to VB.NET before it gets added to your project if it detects that your project is VB.NET.

I’ve tested this as well as I can, but I’d appreciate feedback on how you find it.

DependencyProperty

I’d like to thank Jeremy Robertson, aka Hero, for this one. A couple of weeks back he emailed me to say that he’d come up with an addition to MoXAML, and he sent me the code for the DependencyProperty command. In his own words:

“It’s similar to PropertyManager, except it works on Dependency Properties.
Highlight a group of dependency properties, run the tool, and it will put CLR properties for each dependency property on the clipboard.”

Thanks for that Jeremy – it’s much appreciated.

Downloads

Downloads available here.

Next steps

Well, the next step for me is to produce detailed instructions on how to use MoXAML and XAML Power Toys together to produce a Silverlight application. It’s pretty powerful stuff, and I owe a great debt of gratitude to Karl Shifflett for XAML Power Toys. When you see the combination in action, you can see why we’re doing this.

Beyond that, I’m going to be revisiting the commenting code as per Logan’s requests, and I’m also going to be adding in a new command to convert code from one language to another. Another feature on my wishlist that I’ll be looking at soon is selecting a keyword in your source or XAML and then it will search Google, Live, and so on, to get you help on the keyword.

As always, keep your comments coming in and thanks for your feedback so far.