WPF MVVM – Simple Property Rules Engine

by Dean 9. September 2011 19:47

I'm currently working on a large legacy WPF project where my ViewModels often have a large number of properties, and those properties have some complex inter-relationships that need to be reflected in the behaviour of the app,  via the ViewModels and XAML bindings.

Specifically, some properties may need to support some of the following behaviours:

1) A property may need to invoke a change notification in the UI if a related property changes

2) A property may be a calculated value, and the calculation may rely on other property values which may change.

3) A property may need to support validation

With these requirements in mind, I wrote a simple POC (proof of concept) of a ‘rules engine’ that may provide those features and can be utilised in the ViewModel in a straightforward way.

Below is the code for the rules engine class:

using System;
using System.Collections.Generic;
using System.ComponentModel;

public class PropertyRuleEngine
{
    private readonly Dictionary<string, List<string>> dependencies = 
        new Dictionary<string, List<string>>();
    private readonly Dictionary<string, Action> evaluations = 
        new Dictionary<string, Action>();
    private readonly Dictionary<string, List<Func<string>>> validations = 
        new Dictionary<string, List<Func<string>>>();
    private readonly object source;

    public PropertyRuleEngine(object source)
    {
        this.source = source;
    }

    public PropertyRuleEngine AddDependency(string dependentPropertyName, 
        string propertyName)
    {
        if (!this.dependencies.ContainsKey(propertyName))
        {
            this.dependencies.Add(propertyName, new List<string>());
        }

        if (!this.dependencies[propertyName].Contains(dependentPropertyName))
        {
            this.dependencies[propertyName].Add(dependentPropertyName);
        }

        return this;
    }

    public PropertyRuleEngine AddEvaluatedProperty(string propertyName, 
        Action calculateAction)
    {
        this.evaluations.Add(propertyName, calculateAction);
        return this;
    }

    public PropertyRuleEngine AddValidationProperty(string propertyName, 
        Func<string> validationFunction)
    {
        if (!this.validations.ContainsKey(propertyName))
        {
            this.validations.Add(propertyName, new List<Func<string>>());
        }

        this.validations[propertyName].Add(validationFunction);
        return this;
    }

    public void Notify(string property, PropertyChangedEventHandler handler)
    {
        this.InvokePropertyChangedHandler(property, handler);
        if (!this.dependencies.ContainsKey(property))
        {
            return;
        }

        foreach (string tmp in this.dependencies[property])
        {
            if (this.evaluations.ContainsKey(tmp))
            {
                this.evaluations[tmp]();
            }
            else
            {
                this.InvokePropertyChangedHandler(tmp, handler);
            }
        }
    }

    public IEnumerable<string> GetErrors(string property)
    {
        List<string> result = null;
        if (!this.validations.ContainsKey(property))
        {
            return result;
        }

        foreach (var validation in validations[property])
        {
            var tmp = validation();
            if (!string.IsNullOrEmpty(tmp))
            {
                if (result == null)
                {
                    result = new List<string>();
                }
                result.Add(tmp);
            }
        }
        return result;
    }

    private void InvokePropertyChangedHandler(string propertyName, 
        PropertyChangedEventHandler originalHandler)
    {
        PropertyChangedEventHandler handler = originalHandler;
        if (handler == null)
        {
            return;
        }

        Delegate[] delegates = handler.GetInvocationList();
        foreach (Delegate d in delegates)
        {
            d.DynamicInvoke(new[] { this.source, 
                new PropertyChangedEventArgs(propertyName) });
        }
    }
}

 

And here is the (rather simplistic) test ViewModel that utilises the rules engine. It demonstrates how it handles inter-property dependencies, calculated properties and validation

using System;
using System.ComponentModel;

public class TestDomainObjectViewModel : INotifyPropertyChanged, IDataErrorInfo
{
    private readonly PropertyRuleEngine rulesEngine;
    public event PropertyChangedEventHandler PropertyChanged;

    public TestDomainObjectViewModel()
    {
        this.rulesEngine = new PropertyRuleEngine(this);
        this.rulesEngine
            .AddDependency("TestName", "TestId")
            .AddEvaluatedProperty("TestName", () => 
                this.TestName = string.Format("Name : {0}", this.TestId.ToString()))
            .AddValidationProperty("TestId", () => 
                    this.TestId > 50 ? "Number too big" : string.Empty);
    }

    private string testName;
    public string TestName
    {
        get
        {
            return testName;
        }
        set
        {
            testName = value;
            this.rulesEngine.Notify("TestName", this.PropertyChanged);
        }
    }

    private int testId;
    public int TestId
    {
        get
        {
            return this.testId;
        }
        set
        {
            this.testId = value;
            this.rulesEngine.Notify("TestId", this.PropertyChanged);
        }
    }
        
    public string this[string columnName]
    {
        get
        {
            var result = rulesEngine.GetErrors(columnName);
            if (result == null)
            {
                return null;
            }
            return string.Join(Environment.NewLine, result);
        }
    }

    public string Error
    {
        get
        {
            return null;
        }
    }
}

 

And finally, here is the XAML and (if your new to MVVM) the code-behind file for completeness

 

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <TextBlock Text="ID" />
    <TextBox Text="{Binding TestId, Mode=TwoWay, ValidatesOnDataErrors=True,
        UpdateSourceTrigger=LostFocus}" Grid.Column="1" Width="100">
        <TextBox.Style>
            <Style TargetType="TextBox">
                <Style.Triggers>
                    <Trigger Property="Validation.HasError" Value="True">
                        <Setter Property="ToolTip" 
                                Value="{Binding RelativeSource={RelativeSource Mode=Self}, 
                            Path=(Validation.Errors)[0].ErrorContent}" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>
    <TextBlock Text="Name" Grid.Row="1" />
    <TextBox Text="{Binding TestName, Mode=TwoWay}" Grid.Row="1" Grid.Column="1" 
                Width="100" IsReadOnly="True" />
    <Button Content="Update" Grid.Row="2" />
</Grid>
public MainWindow()
{
    InitializeComponent();
    DataContext = new TestDomainObjectViewModel();
}

Tags: ,

C# | MVVM | WPF | XAML

WPF TreeView – SelectedItem Two Way Binding

by Dean 1. September 2011 07:30

Because the standard WPF TreeView implementation supports Virtualization it is unable to support two way bindings on its SelectedItem property as standard. This makes sense, because with Virtualization you may not have a container (TreeViewItem) available for any particular bound data item at the time you need it (to set its IsSelected property of the TreeViewItem  to ‘True’).

The solution is to use attached properties to force the ItemContainerGenerator to create the necessary containers for each data item. This will break the virtualization support, but that is a price you need to pay for a solution to this issue, so you should only use it on TreeView controls where the lack of Virtualization wont be a significant drawback.

Here is the attached property implementation:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
 
public class DemoAttachedProps
{
    public static DependencyProperty SelectedItemProperty = DependencyProperty.RegisterAttached(
        "SelectedItem", typeof(object), typeof(DemoAttachedProps), 
        new PropertyMetadata(new object(), OnSelectedItemChanged));
 
    public static object GetSelectedItem(TreeView treeView)
    {
        return treeView.GetValue(SelectedItemProperty);
    }
 
    public static void SetSelectedItem(TreeView treeView, object value)
    {
        treeView.SetValue(SelectedItemProperty, value);
    }
 
    private static void OnSelectedItemChanged(DependencyObject d, 
        DependencyPropertyChangedEventArgs args)
    {
        var treeView = d as TreeView;
        if (treeView == null)
        {
            return;
        }
        treeView.SelectedItemChanged -= TreeViewItemChanged;
        var treeViewItem = SelectTreeViewItemForBinding(args.NewValue, treeView);
        if (treeViewItem != null)
        {
            treeViewItem.IsSelected = true;
        }
        treeView.SelectedItemChanged += TreeViewItemChanged;
    }
 
    private static void TreeViewItemChanged(object sender, 
        RoutedPropertyChangedEventArgs<object> e)
    {
        ((TreeView)sender).SetValue(SelectedItemProperty, e.NewValue);
    }
 
    private static TreeViewItem SelectTreeViewItemForBinding(
        object dataItem, ItemsControl ic)
    {
        if (ic == null || dataItem == null)
        {
            return null;
        }
        IItemContainerGenerator generator = ic.ItemContainerGenerator;
        using (generator.StartAt(generator.GeneratorPositionFromIndex(-1), 
            GeneratorDirection.Forward))
        {
            foreach (var t in ic.Items)
            {
                bool isNewlyRealized;
                var tvi = generator.GenerateNext(out isNewlyRealized);
                if (isNewlyRealized)
                {
                    generator.PrepareItemContainer(tvi);
                }
                if (t == dataItem)
                {
                    return tvi as TreeViewItem;
                }
 
                var tmp = SelectTreeViewItemForBinding(dataItem, 
                    tvi as ItemsControl);
                if (tmp != null)
                {
                    return tmp;
                }
            }
        }
        return null;
    }
}

And here is the attached property in action:

public class TestDataObjViewModel
{
    public List<TestDataObj> TestList { get; private set; }
    public List<TestDataObj> TestHierarchy { get; private set; }
 
    public TestDataObjViewModel()
    {
        TestList = new List<TestDataObj>();
        var top = new TestDataObj { TestText = "top" };
        TestList.Add(top);
        var second1 = new TestDataObj { TestText = "second 1" };
        TestList.Add(second1);
        top.Children.Add(second1);
        var second2 = new TestDataObj { TestText = "second 2" };
        TestList.Add(second2);
        top.Children.Add(second2);
        var third = new TestDataObj { TestText = "third" };
        TestList.Add(third);
        second1.Children.Add(third);
        TestHierarchy = new List<TestDataObj> { top };
    }
}
 
public class TestDataObj
{
    private readonly List<TestDataObj> children = new List<TestDataObj>();
 
    public string TestText { get; set; }
 
    public List<TestDataObj> Children
    {
        get
        {
            return children;
        }
    }
}

Here's the code-behind for the demo XAML

public MainWindow()
{
    InitializeComponent();
    DataContext = new TestDataObjViewModel();
}

And here’s the XAML

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <TreeView ItemsSource="{Binding TestHierarchy}" x:Name="treeView" 
              Margin="0,10" DemoApp1:DemoAttachedProps.SelectedItem="{x:Null}" >
        <TreeView.ItemContainerStyle>
            <Style TargetType="TreeViewItem">
                <Setter Property="IsExpanded" Value="True" />
            </Style>
        </TreeView.ItemContainerStyle>
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Children}">
                <TextBlock Text="{Binding TestText}" />
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
    <ComboBox ItemsSource="{Binding TestList}" DisplayMemberPath="TestText" 
              Grid.Row="1" HorizontalAlignment="Left" x:Name="comboBox" 
              SelectedItem="{Binding ElementName=treeView, 
                Path=(DemoApp1:DemoAttachedProps.SelectedItem), Mode=TwoWay}" />
</Grid>

Tags: , , ,

Attached Properties | MVVM | WPF | XAML

WPF – Colour Picker Widget With Attached Properties

by Dean 21. November 2010 08:47

We can set the colour of any WPF control that supports it, but what about being able to specifically sett individual colour channels (RED, GREEN, BLUE, ALPHA)

I've seen many solutions that contain complex custom controls, but one of the key philosophies of WPF is to reuse what you already have, and change the look or extend the functionality via control templates and the dependency system.

Therefore, I have created a colour picker widget that uses only standard controls, and doesn't even change their control templates. Everything is accomplished via the use of attached properties, which are a very underrated tool in the WPF tool-box.

Here’s the attached property class

public static class BrushExtender
{
    public readonly static DependencyProperty BrushProperty =
        DependencyProperty.RegisterAttached("Brush", typeof(Brush), 
        typeof(BrushExtender), new PropertyMetadata(Brushes.Black, DoBrushChanged));

    public readonly static DependencyProperty RedChannelProperty = 
        DependencyProperty.RegisterAttached("RedChannel", typeof(int), 
        typeof(BrushExtender), new PropertyMetadata(DoColorChangedRed));

    public readonly static DependencyProperty GreenChannelProperty = 
        DependencyProperty.RegisterAttached("GreenChannel", typeof(int), 
        typeof(BrushExtender), new PropertyMetadata(DoColorChangedGreen));

    public readonly static DependencyProperty BlueChannelProperty =
        DependencyProperty.RegisterAttached("BlueChannel", typeof(int),
        typeof(BrushExtender), new PropertyMetadata(DoColorChangedBlue));

    public readonly static DependencyProperty AlphaChannelProperty = 
        DependencyProperty.RegisterAttached("AlphaChannel", typeof(int),
        typeof(BrushExtender), new PropertyMetadata(DoColorChangedAlpha));

    public readonly static DependencyProperty ColourValueProperty =
        DependencyProperty.RegisterAttached("ColourValue", typeof(string),
        typeof(BrushExtender), new PropertyMetadata(DoValueChanged));

    public static void SetRedChannel(DependencyObject o, int value)
    {
        o.SetValue(RedChannelProperty, value);
    }

    public static void SetGreenChannel(DependencyObject o, int value)
    {
        o.SetValue(GreenChannelProperty, value);
    }

    public static void SetBlueChannel(DependencyObject o, int value)
    {
        o.SetValue(BlueChannelProperty, value);
    }

    public static void SetAlphaChannel(DependencyObject o, int value)
    {
        o.SetValue(AlphaChannelProperty, value);
    }

    public static void SetBrush(DependencyObject o, SolidColorBrush brush)
    {
        o.SetValue(BrushProperty, brush);
    }

    public static void SetColourValue(DependencyObject o, string value)
    {
        o.SetValue(ColourValueProperty, value);
    }

    private static void DoColorChangedRed(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var color = ((SolidColorBrush)d.GetValue(BrushProperty)).Color;
        DoColorChange(d, (int)e.NewValue, c => c.R, () => 
            Color.FromArgb(color.A, ((byte)(int)e.NewValue), color.G, color.B));
    }

    private static void DoColorChangedGreen(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var color = ((SolidColorBrush)d.GetValue(BrushProperty)).Color;
        DoColorChange(d, (int)e.NewValue, c => c.G, () => 
            Color.FromArgb(color.A, color.R, ((byte)(int)e.NewValue), color.B));
    }

    private static void DoColorChangedBlue(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var color = ((SolidColorBrush)d.GetValue(BrushProperty)).Color;
        DoColorChange(d, (int)e.NewValue, c => c.B, () => 
            Color.FromArgb(color.A, color.R, color.G, (byte)(int)e.NewValue));
    }

    private static void DoColorChangedAlpha(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var color = ((SolidColorBrush)d.GetValue(BrushProperty)).Color;
        DoColorChange(d, (int)e.NewValue, c => c.A, () => 
            Color.FromArgb((byte)(int)e.NewValue, color.R, color.G, color.B));
    }

    private static void DoColorChange(DependencyObject d, int newValue, Func<Color, int> colorCompare, 
        Func<Color> getColor)
    {
        var color = ((SolidColorBrush)d.GetValue(BrushProperty)).Color;
        if (colorCompare(color) == newValue)
            return;
        var newBrush = new SolidColorBrush(getColor());
        d.SetValue(BrushProperty, newBrush);
        d.SetValue(ColourValueProperty, newBrush.Color.ToString());
    }

    private static void DoValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var color = ((SolidColorBrush)d.GetValue(BrushProperty)).Color;
        if (color.ToString() == (string)e.NewValue)
            return;
        Color? newColour = null;
        try
        {
            newColour = (Color) ColorConverter.ConvertFromString((string)e.NewValue);
        }
        catch { }
        if (newColour == null)
            return;
        var newBrush = new SolidColorBrush(newColour.Value);
        d.SetValue(BrushProperty, newBrush);
    }


    private static void DoBrushChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue == e.OldValue)
            return;
        var colour = ((SolidColorBrush)e.NewValue).Color;
        d.SetValue(RedChannelProperty, (int)colour.R);
        d.SetValue(GreenChannelProperty, (int)colour.G);
        d.SetValue(BlueChannelProperty, (int)colour.B);
        d.SetValue(AlphaChannelProperty, (int)colour.A);
        d.SetValue(ColourValueProperty, colour.ToString());
    }
}

And here is the simple WPF widget that makes use of this new functionality

<Window x:Class="ColourBlender.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:ColourBlender="clr-namespace:ColourBlender" 
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <TextBlock Text="Red" />
        <TextBlock Text="Green" Grid.Row="1" />
        <TextBlock Text="Blue" Grid.Row="2" />
        <TextBlock Text="Alpha" Grid.Row="3" />

        <Slider Name="redSlider" Grid.Column="1" Minimum="0" Maximum="255" Width="200" Height="20" 
                Grid.ColumnSpan="2" Value="{Binding ElementName=rect, 
                Path=(ColourBlender:BrushExtender.RedChannel), Mode=TwoWay}" />
        <Slider Name="greenSlider" Grid.Column="1" Grid.Row="1" Minimum="0" Maximum="255" Width="200" Height="20" 
                Grid.ColumnSpan="2" Value="{Binding ElementName=rect, 
                Path=(ColourBlender:BrushExtender.GreenChannel), Mode=TwoWay}"  />
        <Slider Name="blueSlider" Grid.Column="1" Grid.Row="2" Minimum="0" Maximum="255" Width="200" Height="20" 
                Grid.ColumnSpan="2" Value="{Binding ElementName=rect, 
                Path=(ColourBlender:BrushExtender.BlueChannel), Mode=TwoWay}"  />
        <Slider Name="alphaSlider" Grid.Column="1" Grid.Row="3" Minimum="0" Maximum="255" Width="200" Height="20" 
                Grid.ColumnSpan="2" Value="{Binding ElementName=rect, 
                Path=(ColourBlender:BrushExtender.AlphaChannel), Mode=TwoWay}"  />

        <Rectangle Fill="SandyBrown" Name="rect" Width="200" Height="50" Grid.Row="4" Grid.ColumnSpan="3" 
                Margin="0,20,0,10" ColourBlender:BrushExtender.Brush="{Binding RelativeSource={RelativeSource Self}, 
                Path=Fill, Mode=TwoWay}"/>
        
        <TextBlock Text="Colour Value" Margin="5,0,5,0" Grid.Row="5" HorizontalAlignment="Center"  />
        <TextBox Text="{Binding ElementName=rect, Path=(ColourBlender:BrushExtender.ColourValue), Mode=TwoWay}" 
                Margin="0,0,0,0" Grid.Row="5" Grid.Column="1" Width="100" HorizontalAlignment="Center" />
        
        <Button Content="Update" Grid.Row="5" Grid.Column="3" />
    </Grid>
</Window>

This widget allows you to alter the Fill colour of a rectangle via red, green, blue and alpha sliders. There is also a textbox that shows the colour code (which you can also edit and the change is reflected in the slider positions)

Here are some screen shots

 

colour1

colour2

Tags: ,

Attached Properties | DataBinding | WPF | XAML

WPF – Loading Spinner Via MVVM and Attached Properties

by Dean 13. November 2010 14:47

When I used to write a lot of Ajax for ASP.NET (many years ago) I quite like the feature whereby you could disable the page and show a ‘loading spinner’ while waiting for an update in the page.

This is a great feature to have in WPF, so I have created a ViewModel with a ‘loading’ switch (bool), and an attached property that creates and displays the animated spinner (for the duration of the switch flag being true)

Firstly, we need a control template for a content control that will be our animated spinner.

<Style x:Key="LoadingSpinner" TargetType="ContentControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ContentControl">
                <Grid>
                    <Rectangle Width="160" Height="160">
                        <Rectangle.Fill>
                            <VisualBrush Stretch="None">
                                <VisualBrush.Visual>
                                    <Canvas RenderTransformOrigin="0.5,0.5">
                                        <Ellipse Width="14.8333" Height="14.8333" Canvas.Left="71.1667" 
                                                Canvas.Top="3.00002" Stretch="Fill" Fill="#FF000000"/>
                                        <Ellipse Width="14.8333" Height="14.8333" Canvas.Left="71.1667" 
                                                Canvas.Top="139.833" Stretch="Fill" Fill="#85000000"/>
                                        <Ellipse Width="14.8333" Height="14.8333" Canvas.Left="139.583" 
                                                Canvas.Top="71.4167" Stretch="Fill" Fill="#C2000000"/>
                                        <Ellipse Width="14.8333" Height="14.8333" Canvas.Left="2.75" 
                                                Canvas.Top="71.4167" Stretch="Fill" Fill="#48000000"/>
                                        <Ellipse Width="14.8333" Height="14.8333" Canvas.Left="22.7888" 
                                                Canvas.Top="23.0388" Stretch="Fill" Fill="#29000000"/>
                                        <Ellipse Width="14.8333" Height="14.8333" Canvas.Left="119.545" 
                                                Canvas.Top="119.795" Stretch="Fill" Fill="#A4000000"/>
                                        <Ellipse Width="14.8333" Height="14.8333" Canvas.Left="119.545" 
                                                Canvas.Top="23.0388" Stretch="Fill" Fill="#E1000000"/>
                                        <Ellipse Width="14.8333" Height="14.8333" Canvas.Left="22.7888" 
                                                Canvas.Top="119.795" Stretch="Fill" Fill="#67000000"/>
                                        <Ellipse Width="14.8372" Height="14.8372" Canvas.Left="44.9828" 
                                                Canvas.Top="8.20598" Stretch="Fill" Fill="#1A000000"/>
                                        <Ellipse Width="14.8372" Height="14.8372" Canvas.Left="97.3466" 
                                                Canvas.Top="134.623" Stretch="Fill" Fill="#94000000"/>
                                        <Ellipse Width="14.8372" Height="14.8372" Canvas.Left="134.373" 
                                                Canvas.Top="45.2328" Stretch="Fill" Fill="#D2000000"/>
                                        <Ellipse Width="14.8372" Height="14.8372" Canvas.Left="7.95596" 
                                                Canvas.Top="97.5967" Stretch="Fill" Fill="#57000000"/>
                                        <Ellipse Width="14.8372" Height="14.8372" Canvas.Left="7.95596" 
                                                Canvas.Top="45.2328" Stretch="Fill" Fill="#39000000"/>
                                        <Ellipse Width="14.8372" Height="14.8372" Canvas.Left="134.373" 
                                                Canvas.Top="97.5966" Stretch="Fill" Fill="#B3000000"/>
                                        <Ellipse Width="14.8372" Height="14.8372" Canvas.Left="97.3466" 
                                                Canvas.Top="8.20599" Stretch="Fill" Fill="#F0000000"/>
                                        <Ellipse Width="14.8372" Height="14.8372" Canvas.Left="44.9828" 
                                                Canvas.Top="134.623" Stretch="Fill" Fill="#76000000"/>
                                        <Canvas.RenderTransform>
                                            <RotateTransform Angle="0" />
                                        </Canvas.RenderTransform>
                                        <Canvas.LayoutTransform>
                                            <ScaleTransform ScaleX="0.6" ScaleY="0.6" />
                                        </Canvas.LayoutTransform>
                                        <Canvas.Triggers>
                                            <EventTrigger RoutedEvent="ContentControl.Loaded">
                                                <BeginStoryboard>
                                                    <Storyboard>
                                                        <DoubleAnimation 
                                                            Storyboard.TargetProperty=
                                                                "(Canvas.RenderTransform).Angle" 
                                                            From="0" To="360" Duration="0:0:02" 
                                                            RepeatBehavior="Forever" />
                                                    </Storyboard>
                                                </BeginStoryboard>
                                            </EventTrigger>
                                        </Canvas.Triggers>
                                    </Canvas>
                                </VisualBrush.Visual>
                            </VisualBrush>
                        </Rectangle.Fill>
                    </Rectangle>
                    <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The Content property of out content presenter will include our text message that will be inside the spinner

Next we need our attached property class

    public class AsyncNotifier
    {
        public static readonly DependencyProperty TriggerProperty = 
            DependencyProperty.RegisterAttached("Trigger", typeof(bool), typeof(AsyncNotifier), 
            new PropertyMetadata(false, TriggerCallback));

        public static readonly DependencyProperty SpinnerTextProperty = 
            DependencyProperty.RegisterAttached("SpinnerText", typeof(string), typeof(AsyncNotifier));

        private static readonly DependencyProperty SpinnerProperty = 
            DependencyProperty.RegisterAttached("Spinner", typeof(Grid), typeof(AsyncNotifier));

        public static void SetTrigger(DependencyObject d, bool trigger)
        {
            d.SetValue(TriggerProperty, trigger);
        }

        public static void SetSpinnerText(DependencyObject d, string text)
        {
            d.SetValue(SpinnerTextProperty, text);
        }

        private static void TriggerCallback(DependencyObject d,
DependencyPropertyChangedEventArgs e)
        {
            var parentGrid = d as Grid;
            if (parentGrid == null)
                return;
            string spinnerText = (string)parentGrid.GetValue(SpinnerTextProperty);
            bool trigger = (bool)parentGrid.GetValue(TriggerProperty);
            Grid grid = parentGrid.GetValue(SpinnerProperty) as Grid;
            if (grid == null)
            {
                grid = new Grid();
                parentGrid.SetValue(SpinnerProperty, grid);
                if (parentGrid.ColumnDefinitions.Count > 0)
                    Grid.SetColumnSpan(grid, parentGrid.ColumnDefinitions.Count);
                if (parentGrid.RowDefinitions.Count > 0)
                    Grid.SetRowSpan(grid, parentGrid.RowDefinitions.Count);
            }
            grid.Background = new SolidColorBrush(Colors.White) { Opacity = 0.6 };
            grid.Children.Clear();
            ContentControl cont = new ContentControl();
            cont.Content = new TextBlock() { Text = spinnerText };
            cont.Style = (Style)parentGrid.FindResource("LoadingSpinner");
            grid.Children.Add(cont);
            if (!parentGrid.Children.Contains(grid))
                parentGrid.Children.Add(grid);
            grid.Visibility = trigger ? Visibility.Visible : Visibility.Hidden;
        }
    }

Now our ViewModel

public class MainViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public bool IsDataLoading { get; private set; }
    public List<string> TestData { get; private set; }
    public ICommand LoadData { get; private set; }

    public MainViewModel()
    {
        IsDataLoading = false;
        LoadData = new ActionCommand(LoadTestData);
    }

    private void LoadTestData()
    {
        TestData = new List<string>();
        ThreadPool.QueueUserWorkItem((o) => 
            {
                IsDataLoading = true;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("IsDataLoading"));
                for (int i = 0; i < 20; i++)
                    Dispatcher.CurrentDispatcher.Invoke((Action)(() => TestData.Add("Test Data Item " + i)));
                Thread.Sleep(2000);
                IsDataLoading = false;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("IsDataLoading"));
                    PropertyChanged(this, new PropertyChangedEventArgs("TestData"));
                }
            });
    }
}

public class ActionCommand : ICommand
{
    private readonly Action action;
    public ActionCommand(Action action)
    {
        this.action = action;
    }
    public void Execute(object parameter)
    {
        action();
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;
}

Heres out Window that uses the attached property to include a spinner

    <Window.Resources>
        <CollectionViewSource x:Key="DataList" Source="{Binding TestData}"  />
    </Window.Resources>
    <Grid Background="AliceBlue" app:AsyncNotifier.Trigger="{Binding IsDataLoading}" 
          app:AsyncNotifier.SpinnerText="Loading...">
        <TabControl Grid.RowSpan="2">
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5">
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <ListBox ItemsSource="{Binding 
                        Source={StaticResource DataList}}" />
                    <Button Content="Do Update" HorizontalAlignment="Left" Command="{Binding LoadData}"
                            VerticalAlignment="Top" Width="75" Grid.Row="1" Margin="0,5" />
                </Grid>
            </TabItem>
            <TabItem Header="TabItem">
                <Grid Background="#FFE5E5E5"/>
            </TabItem>
        </TabControl>
    </Grid>

And finally our code behind

public MainWindow()
{
    InitializeComponent();
    DataContext = new MainViewModel();
}

And here are some screen shots

Before:

before

During Loading:

during

When Done:

after

Dean

Tags: ,

WPF | XAML | Animation

MVVM – Simple Generic<T> Event Commands With Attached Properties

by Dean 10. November 2010 07:08

One of the challenges of MVVM is to favour command bindings over handling routed events, as currently all event handling must happen in the ‘code behind’ file rather than the ViewModel – which breaks the pattern.

With WPF4 we get the new InputBindings feature, that allows us to hook-up mouse and keyboard gestures to commands, but this still doesn't solve all scenarios where event handling seems to be our only option.

There are many elaborate and highly engineered strategies that I have seen to solve this, but maybe we could use a simple attached property implementation to achieve the desired effect.

Also, WPF bindings (including command bindings) don't support generics, but maybe we could use type inference to create a generic implementation.

In the example below, I have created an attached property that hooks up the ‘Selector’ (base control for ListBox and ListView) ‘SelectionChanged’ routed event to a custom ICommand that can be utilised in our ViewModel

Here's the attached property and command:

 

public class SelectionChangedCommand<T> : ICommand
{
    private readonly Action<List<T>, List<T>> action;

    public SelectionChangedCommand(Action<List<T>, List<T>> action)
    {
        this.action = action;
    }

    public void Execute(object parameter)
    {
        var args = parameter as SelectionChangedEventArgs;
        if (args == null)
            return;
        List<T> added = (
                from object item
                in args.AddedItems
                select (T)item
                ).ToList();
        List<T> removed = (
                from object item
                in args.RemovedItems
                select (T)item
                ).ToList();
        action(added, removed);
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;
}

public static class SelectionChangedCommand
{
    public static DependencyProperty BindProperty = DependencyProperty.RegisterAttached("Bind",
                    typeof(ICommand),
                    typeof(SelectionChangedCommand),
                    new PropertyMetadata(AttachCommand));

    public static void SetBind(DependencyObject d, ICommand command)
    {
        d.SetValue(BindProperty, command);
    }

    private static void AttachCommand(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Selector selector = d as Selector;
        if (selector == null)
            return;
        ICommand oldCommand = e.OldValue as ICommand;
        ICommand newCommand = e.NewValue as ICommand;
        if (oldCommand != null || newCommand == null)
            return;
        selector.SelectionChanged += (o, a) => newCommand.Execute(a);
    }
}

Here’s a test ViewModel where we supply data to the View and well as our command binding:

public class MainViewModel
{
    public List<string> MainList 
    { get; set; }
    public SelectionChangedCommand<string> MainListChanged
    { get; set; }

    public MainViewModel()
    {
        MainList = new List<string> { 
            "testitem1", "testitem2", "testitem3", "testitem4", "testitem5" };
        MainListChanged = new SelectionChangedCommand<string>(DoChange);
    }

    private void DoChange(List<string> addedItems, List<string> removedItems)
    {
        // do viewmodel update here
    }
}

Heres our View

<Window x:Class="MVVMEvents.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:e="clr-namespace:MVVMEvents" 
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox ItemsSource="{Binding MainList}" SelectionMode="Multiple"
               e:SelectionChangedCommand.Bind="{Binding MainListChanged}"/>
    </Grid>
</Window>

And here’s where we hook up our ViewModel to the View (usual code):

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel();
    }
}

And there it is, we’ve hooked up a non-generic Routed Event (SelectionChanged) to a generic command command that fits nicely into our MVVM pattern implementation.

NOTE: This simple implementation doesn't support Weak Events, which would be a worthwhile improvement.

Dean

Tags: , ,

WPF | Silverlight | MVVM | DataBinding | XAML | Events

WPF – Easy INotifyPropertyChanged Via DynamicObject Proxy

by Dean 15. October 2010 07:53

There has been a big debate at the bank about how best to implement INotifyPropertyChanged on Model classes that need to support change notifications.

None of the approaches seem entirely satisfactory, and here is a quick rundown of the main contenders:

  1. Default approach – hard-code string representations of the property name that’s changing –> this is the easiest approach, and the one that’s included in most documentation, but it can quickly introduce subtle binding errors in WPF if you forget to re-write the strings when you refactor your model classes
  2. Derive Model classes from DependencyObject and use the WPF dependency system for change notifications –> This is an effective solution, but breaks down if you want to do good unit testing. Also architecturally its not good, as your model classes now depend on systems designed to support WPF controls.
  3. Wrap your model classes in their own ViewModel that implements the interface –> this is a sound solution, but requires the coding of additional decorator classes, and can lead to a lot of code-bloat.
  4. Use Lambda Expressions –> this is refactor-proof, but is a poor performer as deciphering the lambda expressions in order to get at the property name uses reflection. Even though lambda expressions are lazy-compiled, there’s still a significant performance hit and the coding style seems counter-intuitive, which may confuse junior developers.
  5. Get the name of the current method inside the property setter, and then strip out the ‘set_’ part of the method name –> this is a really ugly solution, and may not work if you obfuscate the code.
  6. Look at the method call stack inside a helper class –> really ugly code and fragile if refactored.
  7. Derive your model classes from ContextBoundObject so they can be automatically remoted, and then inject AOP code into the message sink-chain –> are you serious !!!

None of the approaches are great, and every one requires the original Model class to be modified in order to support the approach.

So I thought – how about a generic class that derives from DynamicObject, and implements INotifyPropertyChanged. With such a class you’d achieve the following:

  1. Automatic property changed notifications without changing a line of code on your model classes
  2. The solution is completely refactor-proof
  3. It performs reasonably well
  4. The additional memory consumption and strain on the GC is negligible.
  5. It a '’one size fits all’ solution

So, here’s my implementation:

public class DynamicBindingProxy<T> : DynamicObject, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private static readonly Dictionary<string, Dictionary<string, PropertyInfo>> properties =
        new Dictionary<string, Dictionary<string, PropertyInfo>>();
    private readonly T instance;
    private readonly string typeName;

    public DynamicBindingProxy(T instance)
    {
        this.instance = instance;
        var type = typeof(T);
        typeName = type.FullName;
        if (!properties.ContainsKey(typeName))
            SetProperties(type, typeName);
    }

    private static void SetProperties(Type type, string typeName)
    {
        var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        var dict = props.ToDictionary(prop => prop.Name);
        properties.Add(typeName, dict);
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (properties[typeName].ContainsKey(binder.Name))
        {
            result = properties[typeName][binder.Name].GetValue(instance, null);
            return true;
        }
        result = null;
        return false;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (properties[typeName].ContainsKey(binder.Name))
        {
            properties[typeName][binder.Name].SetValue(instance, value,null);
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(binder.Name));
            return true;
        }
        return false;
    }
}

 

As you can see, the only minor initial performance hit is when reflecting the classes type for the first time, which is then cached in a static dictionary.

And here is it being used:

public class TestObj
{
    public string Name { get; set; }
    public int ID { get; set;  }
    public DateTime SomeDate { get; set; }
    public double Amount { get; set; }
}

 

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        mc:Ignorable="d" x:Class="WpfApplication1.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <Border Padding="10">
        <Grid HorizontalAlignment="Left" VerticalAlignment="Top">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <UniformGrid Rows="4" Columns="2">
                <TextBlock TextWrapping="Wrap"><Run Language="en-gb" Text="Name"/></TextBlock>
                <TextBox TextWrapping="Wrap" Text="{Binding Name}"/>
                <TextBlock TextWrapping="Wrap"><Run Language="en-gb" Text="ID"/></TextBlock>
                <TextBox TextWrapping="Wrap" Text="{Binding ID}"/>
                <TextBlock TextWrapping="Wrap"><Run Language="en-gb" Text="Amount"/></TextBlock>
                <TextBox TextWrapping="Wrap" Text="{Binding Amount}"/>
                <TextBlock TextWrapping="Wrap"><Run Language="en-gb" Text="Some Date"/></TextBlock>
                <TextBox TextWrapping="Wrap" Text="{Binding SomeDate}"/>
            </UniformGrid>
            <StackPanel HorizontalAlignment="Left" Orientation="Horizontal" Grid.Row="1" 
                        d:LayoutOverrides="Height" Margin="0,10,0,0">
                <TextBox TextWrapping="Wrap" Margin="0,0,10,0" Width="150" Name="newText"/>
                <Button Content="Change Name" Click="UpdateName" d:LayoutOverrides="Width"/>
            </StackPanel>
        </Grid>
    </Border>
</Window>
public partial class MainWindow : Window
{
    private readonly TestObj tObj;
    private DynamicBindingProxy<TestObj> dynObj;
    public MainWindow()
    {
        InitializeComponent();
        tObj = new TestObj() { Name = "test", Amount = 123.45, ID = 44, SomeDate = DateTime.Now };
        dynObj = new DynamicBindingProxy<TestObj>(tObj);
        DataContext = dynObj;
    }

    private void UpdateName(object sender, RoutedEventArgs e)
    {
        ((dynamic)dynObj).Name = newText.Text;
    }
}

As you can see if you run this code, clicking on the update button changes the value of the name property via the dynamic proxy, which publishes the change notification.

 

Dean

Tags: , , ,

C# | DataBinding | MVVM | WPF | XAML

WPF – DataContext Virtualization With Paged Services

by Dean 27. April 2010 21:51

Many WPF applications need to handle a very large data collections – maybe the users really need a million rows in their GridView control. The way we cope with this is to ‘virtualize’ the data, and have it available to your control on an ‘as needed’ basis.

Most list controls in WPF (including the standard ListView/GridView) include the concept of a ‘viewport’ under the hood. A viewport is a virtual ‘window’ on the underlying data collection, which only requires the data currently being displayed – so if your collection is a million rows, and your ‘viewport’ is only 100 rows high, then you only need 100 rows (although they must be the ‘right’ rows).

In addition, if the data collection that is your DataContext implements the non-generic ‘IList’ interface, the viewport will optimize it access to the collection calling the ‘IList.this[index]’ for row enumeration rather than GetEnumerator().

This means that if we create a custom collection that implements the non-generic ‘IList’ interface, we can ‘virtualize’ access to the data – giving us an opportunity to put a million rows in our grid in the blink of an eye.

Also, this ‘million row’ scenario may need to retrieve data from a WCF service (for example), and the service method to retrieve data will most likely be paged, requiring page number and page size parameters to retrieve the correct page.

OK, that’s the intro over, so lets discuss a REALLY easy solution to this requirement

Firstly, I am assuming that you have a service reference to a WCF service that has 2 service methods

  1. A method that gets the total collection count
  2. A method that takes page number and page size parameters and returns a strongly-typed collection representing a single ‘page’ of data

As an example of what I mean, here is a sample service contract for a service I have created for this post

namespace WCFDataPaging.WCF
{
    [ServiceContract]
    public interface IService
    {
 
        [OperationContract]
        List<TestDataObject> GetPageData(int page, int pageSize);
 
        [OperationContract]
        int GetDataCount();
    }
}

and here is my service implementation

public class MainService : IService
{
    public List<TestDataObject> GetPageData(int page, int pageSize)
    {
        return Utility.TestData.Skip(page*pageSize).Take(pageSize).ToList();
    }
 
    public int GetDataCount()
    {
        return Utility.TestData.Count;
    }
}

Now the utility class simple generates a test collection of about a million rows. In real life, these services will be retrieving real data from some kind of data store.

Now I need a collection class on the WPF side, that can perform all of the necessary virtualization:

public sealed class VirtualServiceCollection<T> : IList<T>, IList
{
    private readonly Func<int, int, T[]> dataFunction;
    private readonly Func<int> countFunction;
    private readonly int pageSize;
    private readonly List<T> data;
    private int currentPage;
 
    public VirtualServiceCollection(Func<int,int,T[]> dataFunction, Func<int> countFunction, int pageSize)
    {
        this.dataFunction = dataFunction;
        this.countFunction = countFunction;
        this.pageSize = pageSize;
        data = new List<T>(dataFunction(0, pageSize));
    }
 
    public IEnumerator<T> GetEnumerator()
    {
        var count = countFunction();
        for (var i = 0; i < count; i++)
            yield return this[i];
    }
 
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
 
    public void Add(T item)
    {
        throw new NotImplementedException();
    }
 
    public int Add(object value)
    {
        throw new NotImplementedException();
    }
 
    public bool Contains(object value)
    {
        throw new NotImplementedException();
    }
 
    void IList.Clear()
    {
        DoClear();
    }
 
    public int IndexOf(object value)
    {
        return data.IndexOf((T)value);
    }
 
    public void Insert(int index, object value)
    {
        throw new NotImplementedException();
    }
 
    public void Remove(object value)
    {
        throw new NotImplementedException();
    }
 
    void IList.RemoveAt(int index)
    {
        throw new NotImplementedException();
    }
 
    private T GetItem(int index)
    {
        var bot = currentPage * pageSize;
        var top = Math.Min(bot + pageSize, countFunction());
        if (index >= bot && index < top)
            return data[index - bot];
        currentPage = (int)Math.Floor(index / (double)pageSize);
        data.Clear();
        data.AddRange(dataFunction(currentPage, pageSize));
        return data[index - (currentPage * pageSize)];
    }
 
    object IList.this[int index]
    {
        get { return GetItem(index); }
        set { throw new NotImplementedException(); }
    }
 
    bool IList.IsReadOnly
    {
        get { return false; }
    }
 
    public bool IsFixedSize
    {
        get { return false; }
    }
 
    private void DoClear()
    {
        currentPage = 0;
        data.Clear();
    }
 
    void ICollection<T>.Clear()
    {
        DoClear();
    }
 
    public bool Contains(T item)
    {
        throw new NotImplementedException();
    }
 
    public void CopyTo(T[] array, int arrayIndex)
    {
        throw new NotImplementedException();
    }
 
    public bool Remove(T item)
    {
        throw new NotImplementedException();
    }
 
    public void CopyTo(Array array, int index)
    {
        throw new NotImplementedException();
    }
 
    int ICollection.Count
    {
        get { return countFunction(); }
    }
 
    public object SyncRoot
    {
        get { return this; }
    }
 
    public bool IsSynchronized
    {
        get { return false; }
    }
 
    int ICollection<T>.Count
    {
        get { return countFunction(); }
    }
 
    bool ICollection<T>.IsReadOnly
    {
        get { return false; }
    }
 
    public int IndexOf(T item)
    {
        return data.IndexOf(item);
    }
 
    public void Insert(int index, T item)
    {
        throw new NotImplementedException();
    }
 
    void IList<T>.RemoveAt(int index)
    {
        throw new NotImplementedException();
    }
 
    public T this[int index]
    {
        get { return GetItem(index); }
        set { throw new NotImplementedException(); }
    }
}

One of the things that’s interesting about this is that it takes two Func delegates in its constructor – one to get the collection count, and one to retrieve a page

now, we need to wire it all up

First here’s my WPF code-behind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Loaded += DoLoaded;
    }
 
    private void DoLoaded(object sender, RoutedEventArgs e)
    {
        var s = new ServiceClient();
        var coll = new VirtualServiceCollection<TestDataObject>(s.GetPageData, s.GetDataCount, 100);
        DataContext = coll;
    }
}

As you can see, we pass into our collection the to service methods that get the data we need

And finally – here’s the XAML

<Window x:Class="WCFDataPaging.WPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="Count : " />
            <TextBlock Text="{Binding Path=Count}" />
        </StackPanel>
        <ListView ItemsSource="{Binding}" Grid.Row="1">
            <ListView.View>
                <GridView>
                    <GridView.Columns>
                        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
                        <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" />
                        <GridViewColumn Header="Start Date" DisplayMemberBinding="{Binding StartDate}" />
                        <GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price}" />
                    </GridView.Columns>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

We’ve got a textbox at the top for the count, and the columns for our strongly-typed object

And here it is in action:

virtualdata

This took about half a second to load, and scrolls through the million rows pretty smoothly. FYI the first part of the name column data in my test collection is the row numer, so I can check it’s working :)

 

Dean

Tags: , ,

DataBinding | WCF | XAML | WPF

Using CLR 4 Dynamics To Mock Bindable Objects in XAML

by Dean 3. February 2010 07:45

When I’m building prototypes in WPF or working on a GUI spike in an agile development team I often find it really unproductive to continuously switch between working in XAML (with my designer hat on), and working on the plumbing code (with my C# hat on).

Wouldn't it be nice to be able to model my data in XAML, and seamlessly use it with XAML Binding expressions that’ll be valid once the ‘real’ data gets plumbed in.

Well, thanks to the dynamic features in CLR v4 this is now a trivial task.

Firstly lets look at the XAML – you’ll quickly see the flexibility in using this approach -

<Window x:Class="DynamicWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <collections:Hashtable x:Key="data">
            <sys:Double x:Key="Prop1">50</sys:Double>
            <sys:String x:Key="Prop2">Hello</sys:String>
        </collections:Hashtable>
    </Window.Resources>
    <StackPanel Orientation="Vertical">
        <TextBox Text="{Binding Path=Prop2, Mode=TwoWay}" />
        <TextBlock Text="{Binding Path=Prop2}" />
        <Button Content="{Binding Path=Prop1}" Height="{Binding Path=Prop1}" />
    </StackPanel>
</Window>

The critical thing to look at is the resources section (this could be in a separate resource dictionary if you wanted to keep things neat). Basically, I'm creating a hashtable that is going to model the data I anticipate will be available when I hook it all up after the design phase. Essentially, the hashtable keys are the property names of my object, and the hashtable values are the initial values of the properties.

In the example above, I’m expecting my data object to have 2 properties – one called “Prop1”which is a double, and has an initial value of 50, the other is called “Prop2” which is a string, and has an initial value of “Hello”.

Using the above approach, I could model (or mock) just about any simple object I can imagine.

Now we need to turn this hashtable into a real object, and this is where the new DynamicObject class in CLR 4 comes in.

public class DynamicDataObject : DynamicObject, INotifyPropertyChanged
{
    private Hashtable data;
    public event PropertyChangedEventHandler PropertyChanged;
 
    public DynamicDataObject(Hashtable data)
    {
        this.data = data;
    }
 
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = data.ContainsKey(binder.Name) ? data[binder.Name] : null;
        return true;
    }
 
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        data[binder.Name] = value;
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(binder.Name));
        return true;
    }
}

When you inherit from DynamicObject, your object is essentially ‘dynamic’ which means that it’s members are discovered at runtime. In the class above, I'm using the hashtable passed in as the backing data to enable the correct member resolution at runtime. Effectively, this DynamicDataObject class will correctly mock a compiled CLR object with the same member signature.

Now, all we have to do is hook it up with a single line of code in our code-behind file:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new DynamicDataObject((Hashtable)this.Resources["data"]);
    }
}

And there you have it. The binding expression syntax in your XAML will work seamlessly with this solution. You can specify any type of binding, including the use of valueconverters etc.

Of course, any behaviour you wanted in your data objects cannot be implemented this way, but you shouldn’t mix data and logic anyway :)

 

Dean

Tags: , ,

DataBinding | XAML

RecentComments

Comment RSS
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012 Dean Chalk's Blog