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

前端 未结 1 1869
挽巷
挽巷 2021-01-22 00:31

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\

相关标签:
1条回答
  • 2021-01-22 01:34

    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?

    0 讨论(0)
提交回复
热议问题