ItemsControl内的用户控件的WPF OnPropertyChanged

本文关键字:WPF OnPropertyChanged 控件 用户 ItemsControl | 更新日期: 2023-09-27 18:24:11

我有一个ItemsControl在继承INotifyPropertyChanged的复杂对象的ObservableCollection上重复,为列表中的每个项设置一个用户控件。我的ItemsControl代码是:

<ItemsControl ItemsSource="{Binding Path=.ViewModel.Objects}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <c:UserControl CurrentData="{Binding}" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

现在我的用户控制非常简单。它的工作原理是,我可以从我的ObservableCollection和类似的东西中输出任何文本。下面是我的代码:

public static DependencyProperty CurrentDataProperty = DependencyProperty.Register("CurrentData",
    typeof(MyData),
    typeof(MyUserControl));
public Character CurrentData{
    get {
        return (MyData)GetValue(CurrentDataProperty);
    }
    set {
        SetValue(CurrentDataProperty, value);
    }
}
public MyUserControl() {
    InitializeComponent();
}

我的问题是,我永远无法为CurrentData.OnPropertyChange事件添加事件处理程序。我的XAML绑定,但我希望能够做出一些更复杂的决定,但在MyUserControl()期间,数据将为null。有没有办法将处理程序绑定到这些事件?还是我做得不对?

ItemsControl内的用户控件的WPF OnPropertyChanged

您可以在注册CurrentData依赖属性时指定属性更改回调,然后在回调中挂接事件处理程序(并从旧数据中取消挂接):

public static DependencyProperty CurrentDataProperty = DependencyProperty.Register(
    "CurrentData",
    typeof(MyData),
    typeof(MyUserControl),
    new PropertyMetadata(default(MyData), OnCurrentDataPropertyChanged));
private static void OnCurrentDataPropertyChanged(
    DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    var oldData = e.OldValue as MyData;
    if (oldData != null)
        /* remove event handler(s) for old data */;
    var newData = e.NewValue as MyData;
    if (newData != null)
        /* add event handler(s) for new data */;
}