tags:

views:

318

answers:

1

I'm using WPF and have a data class which I bind to a control's DependencyProperties. I need to change the binding at run time under the control of a user. Ideally I'd like to be able to do something like this

myControl.SetBinding(UserControl.GetDependencyProperty("HeightProperty")
    , myBinding);

Of course GetDependencyProperty taking a string doesn't work, I've got around this by creating my own static class

        public static DependencyProperty GetDP(string Name)
        {
            switch (Name)
            {
                case "Height": return UserControl.HeightProperty;
                case "Width": return UserControl.WidthProperty;
....
            }

Is there a better way?

+1  A: 

You haven't described how the user changes the target dependency property. Can you just store the DependencyPropertys themselves rather than strings? That way you don't have to do any conversion at all. Pseudo-code:

//just an array of all allowable properties
public DependencyProperty[] AllowedProperties { get; }

//the property the user has chosen
public DependencyProperty ChosenProperty { get; set; }

//called whenever ChosenProperty changes
private void OnChosenPropertyChanged()
{
    //redo binding here, using ChosenProperty as the target
}

Edit after comments: You can use DependencyPropertyDescriptor.FromName to get a DependencyProperty from its name, assuming you know the type of the owner:

var descriptor = DepedencyPropertyDescriptor.FromName(nameFromExcel, typeof(YourUserControl), typeof(YourUserControl));
var dependencyProperty = descriptor.DependencyProperty;

HTH, Kent

Kent Boogaart
The user for various reasons will be driving this from Excel, hence needing to convert a string, the contents of an Excel cell to a DP. I like your AllowedProperties idea, but will still have the issue with ChosenProperty.
MrTelly
I see. I've updated my post accordingly.
Kent Boogaart
Thats exactly what I was after - cheers. BTW Your resizer code helped me out of a hole a while back - thanks again
MrTelly