Reputation: 14875
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?
Upvotes: 0
Views: 845
Reputation: 178810
You haven't described how the user changes the target dependency property. Can you just store the DependencyProperty
s themselves rather than string
s? 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;
Upvotes: 1