Zerbu
Zerbu

Reputation: 585

Is it possible to bind to a property using reflection in WPF?

I'm writing code to generate a bunch of textboxes attached to property. Is there any way you can set the source to a property found using reflection, stored as PropertyInfo?

Code for going through the properties:

foreach(PropertyInfo prop in GetType().GetProperties())
{
    UI.Text ctrl = new UI.Text(prop.Name, prop.GetValue(this).ToString(), prop);
    sp.Children.Add(ctrl);
}

(Note: UI.Text is a custom control that contains the TextBox, and sp is a StackPanel)

Binding code:

Binding bind = new Binding() { Source = prop };
if (prop.CanWrite)
{
    TextBox.SetBinding(TextBox.TextProperty, bind);
}
else
{
    TextBox.IsEnabled = false;
}

I currently get the error "Two-way binding requires Path or XPath" which usually occurs when trying to bind to a read-only property. Since the code is protected against that, it's obvious that simply binding to the PropertyInfo doesn't bind to the property itself.

Upvotes: 3

Views: 2215

Answers (1)

mm8
mm8

Reputation: 169210

Set the Path property of the Binding to prop.Name and the Source property to this or whatever object that you want to bind to:

Binding bind = new Binding() { Path = new PropertyPath(prop.Name), Source = this };
if (prop.CanWrite)
{
    TextBox.SetBinding(TextBox.TextProperty, bind);
}
else
{
    TextBox.IsEnabled = false;
}

The Path of a Binding specifies the property to bind to and the Source property specifies the object in which this property is defined.

Upvotes: 3

Related Questions