嵌套的ViewModel设置为MainWindow DataContext:
var mainWindow = new MainWindow();
mainWindow.Show();
mainWindow.DataContext = new
{
MyProperty = new
{
MySubProperty = "Hello"
}
}
在XAML中很容易绑定到MySubProperty:
<Button Content="{Binding MyProperty.MySubProperty}"/>
我该如何在后面的代码中进行绑定?
// MyButton.xaml.cs
public partial class MyButton : Button
{
public MyButton()
{
InitializeComponent();
// todo: add binding here
}
// I want this method called if this datacontext is set.
// and called if MySubProperty changes and INotifyPropertyChange is implemented in the Datacontext.
public void MySubPropertyChanged(string newValue)
{
// ...
}
}
我无法访问MyButton.xaml.cs中的MainWindow,因此无法将其用作源。
Button只是一个例子,但这只是一个开始。
在我的原始方案中,我没有有用的依赖项属性。如果dp对于这种绑定是必需的,那么一个示例将非常有用,其中包括创建dp。
最佳答案
这个怎么样? (只是一个肮脏的例子,未经测试,原则上应该可以工作)
// MyButton.xaml.cs
public partial class MyButton : Button
{
public MyButton()
{
InitializeComponent();
this.DataContextChanged += DataContext_Changed;
}
private void DataContext_Changed(Object sender,DependencyPropertyChangedEventArgs e)
{
INotifyPropertyChanged notify = e.NewValue as INotifyPropertyChanged;
if(null != notify)
{
notify.PropertyChanged += DataContext_PropertyChanged;
}
}
private void DataContext_PropertyChanged(Object sender,PropertyChangedEventArgs e)
{
if(e.PropertyName == "MySubProperty")
MySubPropertyChanged((sender as YourClass).MySubProperty);
}
public void MySubPropertyChanged(string newValue)
{
// ...
}
}
编辑:
用于绑定代码背后的东西,您可以使用:
Binding binding = new Binding();
// directly to myproperty
binding.Source = MyProperty;
binding.Path = new PropertyPath("MySubProperty");
// or window
binding.Source = mainWindow; // instance
binding.Path = new PropertyPath("MyProperty.MySubProperty");
// then wire it up with (button is your MyButton instance)
button.SetBinding(MyButton.MyStorageProperty, binding);
//or
BindingOperations.SetBinding(button, MyButton.MyStorageProperty, binding);