Co-opting Binding to listen to PropertyChanged events without a FrameworkElement

喜夏-厌秋 提交于 2019-12-20 02:56:08

问题


I have some nested view models that implement INotifyPropertyChanged. I'd like to bind an event listener to a nested property path (e.g. "Parent.Child.Name"), much like FrameworkElement dependency properties can be bound to arbitrary nested properties.

However, I just want something like a PropertyChanged event listener -- I don't actually have any UI element I'd like to bind. Is there any way to use the existing framework to set up such an event source? Ideally, I shouldn't need to modify my view model classes (as this is not required for regular data binding in Silverlight).


回答1:


You can certainly co-opt the binding/dependency-property infrastructure to listen for changes to a nested property. The code below is WPF but I believe you can do something similar in Silverlight:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = new Parent { Child = new Child { Name = "Bob" } };
        this.SetBinding(ChildNameProperty, new Binding("Child.Name"));
    }

    public string ChildName
    {
        get { return (string)GetValue(ChildNameProperty); }
        set { SetValue(ChildNameProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ChildName.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ChildNameProperty =
        DependencyProperty.Register("ChildName", typeof(string), typeof(MainWindow), new UIPropertyMetadata(ChildNameChanged));

    static void ChildNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        MessageBox.Show("Child name is now " + e.NewValue);
    }
}

So I've defined my own DependencyProperty, not part of any UI per se (just the MainWindow class), and bound "Child.Name" to it directly. I'm then able to be notified when Child.Name changes.

Will that work for you?



来源:https://stackoverflow.com/questions/7882393/co-opting-binding-to-listen-to-propertychanged-events-without-a-frameworkelement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!