mardi 27 décembre 2016

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.





Aucun commentaire:

Enregistrer un commentaire