简体   繁体   中英

WPF OnPropertyChanged for User Control inside ItemsControl

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?

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 */;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM