0

Qeustion:

Is it possible to add an additional PropertyDescriptor to the PropertyDescriptorCollection of an ICustomTypeDescriptor after DataConext has been set?

Details:

I am creating a new class which implements ICustomTypeDescriptor with the goal of dynamically adding new Properties to this class at runtime, and binding them to a WPF application.

For example, a user may define a new property through a scripting language (eg. Lua) while the app is running, and I would like XAML to be able to Bind to that Property.

The issue I am running into is that if I add a property AFTER the DataContext has been set, the Binding to XAML does not work; it does not attempt to call associated PropertyDescriptor.GetValue method.

I believe this issue is that shortly after setting the DataContext to my ICustomTypeDescriptor, its implementation of ICustomTypeDescriptor.GetProperties is called, at which point I create PropertyDescriptor for all known Properties. I then later add new Properties, but don't have the ability to add new PropertyDescriptor for them.

Code:

I have trimmed down the code a bit here to make it easier to read, removing a lot of the boiler-plate stuff.

The idea in this example is that the first text field is Bound to a dynamically created property, which is defined during construction, and the second text field is Bound to a property that won't exist until the Button is clicked.

The property created when the button is clicked only gets DataBound properly if I set the DataContext to something new.

public class MyCustomType : ICustomTypeDescriptor, INotifyPropertyChanged
{
    Dictionary<string, object> Properties = new Dictionary<string, object>();

    public event PropertyChangedEventHandler PropertyChanged;

    public MyCustomType()
    {
        Properties.Add("CustomProp", "What up, world?");
    }

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }

    public void CreateOrSetProperty(string name, object val)
    {
        Properties[name] = val;
        NotifyPropertyChanged(name);
    }

    PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
    {
        List<PropertyDescriptor> props = new List<PropertyDescriptor>();

        foreach (KeyValuePair<string, object> entry in Properties)
        {
            props.Add(new MyCustomTypePropertyDescriptor(entry.Key, attributes));
        }

        return new PropertyDescriptorCollection(props.ToArray());
    }

    PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
    {
        return ((ICustomTypeDescriptor)this).GetProperties(null);
    }

    class MyCustomTypePropertyDescriptor : PropertyDescriptor
    {
        public MyCustomTypePropertyDescriptor(string name, Attribute[] attrs)
            : base(name, attrs)
        {
        }

        public override object GetValue(object component)
        {
            return ((MyCustomType)component).Properties[Name];
        }

        public override bool IsReadOnly
        {
            get { return false; }
        }

         public override void SetValue(object component, object value)
        {
            ((MyCustomType)component).Properties[Name] = value;
        }
    }
}

public partial class Page5
{
    public Page5()
    {
        this.InitializeComponent();
    }

    private void BtnAddProperty_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        // A static resource defined in XAML used as the DataContext for both text blocks.
        MyCustomType c = Resources["MyCustomTypeData"] as MyCustomType;

        // Create a new property which is already being referenced in a DataBind in XAML but 
        // prior to this function being called, did not exist.
        c.CreateOrSetProperty("AnotherProp", "Another Property!");

        // If I clear the DataContext and set it back to the previous value it triggers 
        // ICustomTypeDescriptor.GetProperties to get called again, and the property gets
        // Bound. If I don't do this, it fails.
        //MyTextBlock2.DataContext = null;
        //MyTextBlock2.DataContext = c;
    }
}

<Page.Resources>
    <WpfApplication1:MyCustomType x:Key="MyCustomTypeData"/>
</Page.Resources>

<Grid x:Name="LayoutRoot">
    <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
        <TextBlock DataContext="{StaticResource MyCustomTypeData}" x:Name="MyTextBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding CustomProp}" VerticalAlignment="Top" FontSize="32" Background="Black" Foreground="White"/>
        <TextBlock DataContext="{StaticResource MyCustomTypeData}" x:Name="MyTextBlock2" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding AnotherProp}" VerticalAlignment="Top" FontSize="32" Background="Black" Foreground="White"/>
        <Button x:Name="BtnAddProperty" Content="Add Additional Property" Click="BtnAddProperty_Click"/>
    </StackPanel>
</Grid>

1 Answer 1

0

I don't fully understand your question. However, I guess it maybe part of your problem that you use a Dictionary in a binding expression. In my opinion the collection which will be bound in xaml should be a type derrived from ObservableCollection in order to own the ability to notify view when collection change.

1
  • I am binding through an instance of ICustomTypeDescriptor, and writing a custom PropertyDescriptor. The dictionary should be irrelevant I believe. It is just how I chose to store my Property data.
    – Goose
    Jan 22, 2014 at 2:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.