更改我在运行时绑定的DependencyProperty

时间:2009-04-01 06:09:45

标签: wpf binding

我正在使用WPF并且有一个数据类,我绑定到控件的DependencyProperties。我需要在用户的控制下在运行时更改绑定。理想情况下,我希望能够做到这样的事情

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

当然GetDependencyProperty取一个字符串不起作用,我通过创建自己的静态类来解决这个问题

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

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

您尚未描述用户如何更改目标依赖项属性。你可以只存储DependencyProperty s而不是string s吗?这样你根本不需要进行任何转换。伪代码:

//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
}

在评论后编辑:您可以使用DependencyPropertyDescriptor.FromName从其名称中获取DependencyProperty,假设您知道所有者的类型:

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