问题
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