将标准属性更改为依赖项属性

本文关键字:属性 依赖 标准 | 更新日期: 2023-09-27 17:56:01

在开发一些供内部使用的用户控件时,我遵循了MSDN http://msdn.microsoft.com/en-us/library/vstudio/ee712573(v=vs.100)中的这个示例.aspx

一个控件的公共值由另一个控件使用。 我目前的工作方式是通过代码隐藏挂接到第一个控件中触发的事件。 我在想使一个或两个属性成为依赖项属性,这将消除对代码隐藏的需求。

public partial class UserControl1 : UserControl
{
    private DataModel1 dm;
    public UserControl1()
    {
        this.DataContext = new DataModel1();
        dm = (DataModel1)DataContext;
        InitializeComponent();
    }
    public DataValue CurrentValue
    {
        get { return dm.CurrentValue; }
        set { dm.CurrentValue = value; }
    }
}
public class DataModel1 : INotifyPropertyChanged
{
    private DataValue _myData = new DataValue();
    public DataValue CurrentValue
    {
        get { return _myData; }
        set { if (_myData != value) {_myData = value OnPropertyChanged("CurrentValue"); }
    }
    // INotifyPropertyChanged Section....
}

该属性只是从DataModel1类传递的。

这两个用户控件在结构上非常相似,并且具有相同的公共属性。我想用类似的绑定替换事件处理程序背后的代码,我认为:

<my:UserControl1 Name="UserControl1" />
<my:UserControl2 CurrentValue={Binding ElementName="UserControl1", Path="CurrentValue"} />

但是 DependencyProperties 的标准示例具有使用 GetValueSetValue 函数的 getter 和 setter,它们使用生成的支持对象而不是允许传递。

public DataValue CurrentValue
{
    get { return (DataValue)GetValue(CurrentValueProperty); }
    set { SetValue(CurrentValueProperty, value); }
}

我认为 DP 应该看起来像:

public static readonly DependencyProperty CurrentValueProperty = 
        DependencyProperty.Register("CurrentValue", typeof(DataValue), typeof(UserControl1));

如何更改公共支持属性的定义以支持数据绑定传递?

将标准属性更改为依赖项属性

我发现跳转到OnPropertyChanged事件允许我将数据传递到DataModel1。 我不是100%确定这是正确的答案,但它可以完成工作。

以下是更正后的代码:

public static readonly DependencyProperty CurrentValueProperty =
       DependencyProperty.Register("CurrentValue", typeof(DataValue), typeof(UserControl1),
       new PropertyMetadata(new PropertyChangedCallback(OnCurrenValueChanged)));
private static void OnCurrentValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        UserControl1 uc = d as UserControl1;
        if (e.NewValue != null)
        {
            uc.dm.CurrentValue = e.NewValue as DataValue;
        }
    }
public DataValue CurrentValue
{
        get { return GetValue(CurrentValueProperty) as DataValue; }
        set { SetValue(CurrentValueProperty, value); }
    }