0

在开发一些供内部使用的用户控件时,我遵循了 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 的标准示例有 getter 和 setter,它们使用GetValueSetValue函数,它们使用生成的支持对象而不是允许通过。

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

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

4

1 回答 1

0

I found that jumping into the OnPropertyChanged event allowed me to pass the data through to the DataModel1. I am not 100% sure that this is the correct answer but it gets the job done.

Here is the corrected code:

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); }
    }
于 2013-01-28T15:23:28.590 回答