05 November 2011

Silverlight - Bindable DataGridColumn headers

When using a DataGrid in Silverlight, you might want to bind it's column headers. For localization purposes for instance. You can't bind the DataGridColumns Header property though, because it's not a dependency property. There is a work-around though, using a behaviour:

Interactivity

To use behaviour, you'll need System.Windows.Interactivity.dll. This one comes with Expression Blend. If you don't have that, you'll find it somewhere on the web.

The behaviour

The behaviour is in this class:
public class BindableColumnHeader : Behavior {
  public object Header {
    get { return GetValue(HeaderProperty); }
    set { SetValue(HeaderProperty, value); }
  }
  public static readonly DependencyProperty HeaderProperty = 
         DependencyProperty.Register("Header",
           typeof(object),
           typeof(BindableColumnHeader),
           new PropertyMetadata(
             new PropertyChangedCallback(HeaderBindingChangedHandler)));

  private static void HeaderBindingChangedHandler(
                      DependencyObject o,
                      DependencyPropertyChangedEventArgs e) {
    var behave = o as BindableColumnHeader;
    if (behave != null && behave.AssociatedObject != null)
      behave.AssociatedObject.Header = e.NewValue;
  }

  protected override void OnAttached() {
    if (this.AssociatedObject != null)
      this.AssociatedObject.Header = this.Header;
    base.OnAttached();
  }
}
It needs that .dll from before.

The DataGrid

To use the behaviour in the grid, you'll need both the interactivity dll (i:). and the behaviour class (synbus:). Then define a column like so:
<data:datagridtextcolumn binding="{Binding Customer}">
  <i:interaction.behaviors>
    <synbus:bindablecolumnheader header="{Binding Whatever}" />
  </i:interaction.behaviors>
</data:datagridtextcolumn>

No comments:

Post a Comment