Dynamic object with notification – DynamicDictionary

December 12th, 2009

I’ve been experimenting recently with dynamic in C# 4.0 and WPF.  I created a very simple class that supports adding members at runtime as well as property change notification for binding.  WPF 4.0 supports binding to dynamic objects.

Test Code:

dynamic testObj = new DynamicDictionary();
testObj.Test = 123;
testObj.Test2 = 345;

You can bind to dynamic object instances in WPF just like any other object.

<TextBlock Text=”{Binding testObj.Test}”/>

If the value of testObj.Test changes when bound to the TextBlock, then the value displayed will update.  If DynamicDictionary did not implement INotifyPropertyChanged, then the TextBlock value would not change.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Dynamic;
using System.ComponentModel;

namespace DynamicData
{
    public class DynamicDictionary : DynamicObject, INotifyPropertyChanged
    {
        public DynamicDictionary()
        {
            InternalValues = new Dictionary<string, object>();
        }
        public DynamicRow Row { get; protected set; }
        protected Dictionary<string, object> InternalValues { get; set; }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            return InternalValues.TryGetValue(binder.Name, out result);
        }
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {

            InternalValues[binder.Name] = value;
            FirePropertyChanged(binder.Name);
            return true;
        }

        public void FirePropertyChanged(string propName)
        {
            var propChange = PropertyChanged;
            if (propChange != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Comments are closed.