Search Results

Keyword: ‘markup extension’

Format WPF Bindings With Resource File Lookups

March 21st, 2009

This post explains a pattern that combines Data Binding, the new StringFormat property and resource lookups through the application of a custom MarkupExtension.



Microsoft introduced the StringFormat property with SP1 for .NET 3.5. StringFormat often eliminates the need for a custom converter if you just need to format a bound value.
Here’s a very simple sample that displays hello xxx on the screen (where “xxx” is the value entered in a TextBox control:


    Text="world" />

    Text="{Binding ElementName=name,
                   StringFormat=hello {0}}" />


Resource Files

I often use resource files to store strings – not only for localization tasks but also in order to maintain strings that are intended for users at a central place. My resource strings often contain placeholders which are populated at runtime using String.Format:




//use resource file to create message
var msg = Resources.Ask_Whether_To_Connect_To_New_Share;
msg = String.Format(msg, configuration.Name);

//display dialog
MessageBoxResult doConnect = Dialogs.ShowYesNo(msg);



Bringing Bindings and Resource Files Together

In the sample above, I accessed the resource file programmatically. In XAML however, I prefer a declarative approach. In order to get there, I implemented a simple MarkupExtension that allows me to do just that:


<!-- Display a formatted text --> <TextBlock x:Name="Title" Text="{Binding Path=Name, StringFormat={ext:Resource Ask_Whether_To_Connect_To_New_Share}}"



The above snippet results in a formatted text being displayed:



Resource MarkupExtension

Here’s the markup extension. As you can see, it’s fairly trivial. Do note that the reference to the application’s Resources file is hardcoded – you will have to set a using statement or adjust that line in order to use your custom resource file.


/// <summary>
/// A markup extension that provides simple access to a given
/// entry in the application's <see cref="Resources"/> file.
/// </summary>
public class Resource : MarkupExtension
  /// <summary>
  /// The resource key to be used for the lookup.
  /// </summary>
  public string ResourceKey { get; set; }

  /// <summary>
  /// Inits the <see cref="Resource"/> markup extension
  /// with the key to be assigned.
  /// </summary>
  /// <param name="resourceKey">The resource key to be assigned.</param>
  public Resource(string resourceKey)
    ResourceKey = resourceKey;

  /// <summary>
  /// Performs a lookup for the defined <see cref="ResourceKey"/>.
  /// </summary>
  /// <returns>
  /// The value of the resource that is specified by the
  /// <see cref="ResourceKey"/> property. If the property is not
  /// set, a null reference is returned.
  /// </returns>
  public override object ProvideValue(IServiceProvider serviceProvider)
    if (String.IsNullOrEmpty(ResourceKey)) return null;
    return Resources.ResourceManager.GetObject(ResourceKey);


Enjoy 🙂

Author: Categories: WPF Tags: ,

Combining WPF Validation Rules and IDataErrorInfo to Resolve Conversion Errors

January 8th, 2009

This article discusses a few approaches to overcome binding conversion errors in WPF by combining model validation (through IDataErrorInfo) and WPF validation rules. Practically, I’m going to outline three approaches to the same solution:

  • Inline declaration
  • Using attached properties
  • Using custom binding classes



The Problem

WPF validation through IDataErrorInfo is a great feature if you already have validation logic in you model. However: There is a problem if the user enters a value that cannot be written to model due to value conversion errors. Let’s start with a simple sample:

  • A TextBox is bound to a numeric Age property of your model.
  • As soon as the user enters a value in the Textbox, the property on the model is updated. The model then validates whether the entered value is valid (range from 1 to 130 years).
  • However: If the user enters a string rather than a number (e.g. “30a”), the value conversion to an integer fails. In this case, WPF does not show an error at all:



Karl Shifflet recently updated his article on this very subject, where he outlines an MVVM-based approach to the problem (highly recommended reading material!).

In my case, however, I was looking for a simpler solution. I had validation and views already in place and just wanted a visual representation of invalid input that cannot be bound to the model.


WPF Validation Rules to the Rescue

And this is where the good old WPF Validation Rules come back into play:

  1. A binding with ValidatesOnDataErrors=True ensures that the model validation logic is being invoked.
  2. Additional WPF Validation Rules take care of invalid input that can not be bound to the model.


<TextBox x:Name="txtAge">
    <Binding Path="Age" ValidatesOnDataErrors="True">
        <rules:NumericRule />



That’s it already! An invalid numeric value (below minimum, above maximum) is handled by the model, everything else is caught be the NumericRule (see attached sample for the sources).



Simplify Markup 1: Attached Properties

The above sample has one catch – it forces me to write rather verbose XAML. This is where attached properties come to the rescue. Here’s the same thing using an attached property:


<TextBox x:Name="txtAge"
  Text="{Binding Path=Age, ValidatesOnDataErrors=True}"
  rules:Editors.TextRule="{StaticResource numericRule}"  


In the sample above, I declared an attached property of type ValidationRule that points to by custom rule. However, depending on your case, you can make your attached property as simple/complex as you need. A great article on this subject was published by WPF master Josh Smith on CodeProject, where he outlines this exact pattern.


Simplify Markup 2: Custom Binding Classes

As an alternative to attached properties – especially in case you want to define multiple parameters – a custom binding expression might be a simpler approach. If you use a simple Decorator helper class, creating your custom binding class is a breeze:


<TextBox x:Name="txtCustomBinding"
  Text="{local:RuleBinding Path=Age, MinValueOverride=20}"


Here’s my custom binding class, derived from BindingDecoratorBase:

using System;
using System.Windows.Controls;
using System.Windows.Data;
using Hardcodet.Wpf.ValidationRules;

namespace Hardcodet.Wpf.CustomBinding
  /// <summary>
  /// A binding extension that checks for a given
  /// numeric value.
  /// </summary>
  public class RuleBinding : BindingDecoratorBase
    /// <summary>
    /// An optional override for the minimum value,
    /// that can be used to narrow the allowed range.
    /// </summary>
    public int? MinValueOverride { get; set; }

    /// <summary>
    /// Creates a new instance of the binding with default values.
    /// </summary>
    public RuleBinding()
      //set default binding directives
      ValidatesOnDataErrors = true;
      UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

    /// <summary>
    /// This method is being invoked during initialization.
    /// </summary>
    /// <param name="provider">Provides access to the bound items.</param>
    /// <returns>The binding expression that is created by
    /// the base class.</returns>
    public override object ProvideValue(IServiceProvider provider)
      //create the validation rule
      ValidationRule rule;
      if (MinValueOverride.HasValue)
        //create a rule that also narrows the minimum value
        rule = new MinNumericRule() {MinValue = MinValueOverride.Value};
        //just make sure the value is numeric
        rule = new NumericRule();


      //delegate binding creation etc. to the base class
      object val = base.ProvideValue(provider);
      return val;


The attached sample shows you all the techniques I described above.

Download sample project:

kick it on

Author: Categories: Uncategorized Tags: ,