【问题标题】:Changing standard property into a DependencyProperty将标准属性更改为 DependencyProperty
【发布时间】:2013-01-26 00:07:13
【问题描述】:

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

一个控件的公共值被另一个控件使用。我目前的工作方式是通过代码隐藏连接到第一个控件中触发的事件。我正在考虑制作一个或两个属性 DependencyProperties,这将消除对代码隐藏的需要。

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 类的传递。

两个 UserControl 的结构非常相似,并且具有相同的公共属性。我想用类似的 Binding 替换 eventhandler 后面的代码,我想:

<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));

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

【问题讨论】:

    标签: c# wpf-controls dependency-properties


    【解决方案1】:

    我发现跳入 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); }
        }
    

    【讨论】:

      猜你喜欢
      • 2012-04-02
      • 1970-01-01
      • 2013-11-02
      • 2016-07-21
      • 1970-01-01
      • 2021-07-31
      • 2012-09-18
      • 2019-07-08
      • 1970-01-01
      相关资源
      最近更新 更多