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?
You haven’t described how the user changes the target dependency property. Can you just store the
DependencyPropertys themselves rather thanstrings? That way you don’t have to do any conversion at all. Pseudo-code:Edit after comments: You can use DependencyPropertyDescriptor.FromName to get a DependencyProperty from its name, assuming you know the type of the owner: