Reputation: 5412
I have an ItemsControl repeating over a ObservableCollection of complext objects that inherit INotifyPropertyChanged to put up a User Control for each item in the list. My code for the ItemsControl is:
<ItemsControl ItemsSource="{Binding Path=.ViewModel.Objects}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<c:UserControl CurrentData="{Binding}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Right now I have the the User Control pretty simple. It works in that I am able to output any text from my ObservableCollection and stuff like that. Below is my code for it:
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();
}
My issue is that there is never a point where I can add an event handler for my CurrentData.OnPropertyChange
event. My XAML binds, but I want to be able to make some more complex decisions, but during MyUserControl()
the data will be null. Is there a way to bind handlers to those events? Or am I doing all of this incorrectly?
Upvotes: 1
Views: 305
Reputation: 25623
You can specify a property change callback when you register your CurrentData
dependency property, and then hook up the event handlers in the callback (and unhook them from the old data):
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 */;
}
Upvotes: 2