Steven
Steven

Reputation: 29

WPF Reflection, Late Binding

I am trying to set properties on WPF controls (height, width, fontweight, margin and many others) from data that is read through an XML file. I am not going to know what properties are going to be set beforehand. I was wondering if anyone knows a way to do this through reflection?

At the moment I have managed to assign all of the primitive types and enum types using reflection but I am having a little bit of trouble with properties like FontWeight, Margin, Background and many others that require other objects in setting the property for instance: To set a FontWeight property of a button you have to do it like this.

button.FontWeight = Fontweights.Bold;

or a Margin

button.Margin = new Thickness(10, 10, 10, 10);

As there are a possible 150 + properties that could be set on the controls in WPF I just wanted to avoid this sort of code.

public void setProperties(String propertyName, string PropertyValue
{

     if(propertyName = "Margin")
     {
         Set the margin.....
     }
     else if (propertyName = "FontWeight")
     {
         set the FontWeight....
     }
}

and so on for each possible property that can be set on WPF controls.

Upvotes: 0

Views: 1557

Answers (3)

jbtule
jbtule

Reputation: 31809

It's actually really simple. You read your string values into properties on a ViewModel, set that view model to your DataContext, and in xaml bind up your properties. Binding uses TypeConverters automatically.

Upvotes: 1

svick
svick

Reputation: 245008

Behind the scenes, XAML uses TypeConverters to convert from string to the specified type. You can use them yourself, since each of the types you mentioned has a default TypeConverter specified using the TypeConverterAttribute. You can use it like this (or alternatively, make the method generic):

object Convert(Type targetType, string value)
{
    var converter = TypeDescriptor.GetConverter(targetType);
    return converter.ConvertFromString(value);
}

Then each of the following works as expected:

Convert(typeof(Thickness), "0 5 0 0")
Convert(typeof(FontWeight), "Bold")
Convert(typeof(Brush), "Red")

Upvotes: 1

Bala R
Bala R

Reputation: 109017

You can do something like this

typeof(Button).GetProperty("FontWeight").SetValue(button1,GetFontWeight("Bold"), null);

EDIT:

You can have a mapping function that convert string to property value

FontWeight GetFontWeight(string value)
{

   swithc(value)
   {
     case "Bold" : return FontWeights.Bold; break;
     ...
   }

}

Upvotes: 0

Related Questions