我有一个ItemsControl重复一个对象的ObservableCollection,它继承了INotifyPropertyChanged,为列表中的每个项目建立了一个User Control。我对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()
期间,数据将为空。有没有办法将处理程序绑定到这些事件?或者我做错了所有这些?
答案 0 :(得分:2)
您可以在注册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 */;
}