[英]Binding to property in nested objects in code behind
嵌套的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)
{
// ...
}
}
編輯:
在codebehind中綁定一些東西你可以使用:
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);
在我原來的問題中,我沒有依賴屬性。 所以我創建了一個。
public partial class MyButton : Button
{
//...
public string MyStorage
{
get { return (string)GetValue(MyStorageProperty); }
set { SetValue(MyStorageProperty, value); }
}
public static DependecyProperty MyStorageProperty =
DependencyProperty.Register("MyStorage", typeof(string), typeof(MyButton),
new UIPropertyMetadata(OnMyStorageChanged));
public static void OnMyStorageChanged(DependecyObject d, DependencyPropertyChangedEventArgs e)
{
var myButton = d as MyButton;
if (myButton == null)
return;
myButton.OnMyStorageChanged(d,e);
}
public void OnMyStorageChanged(object sender, DependencyPropertyChangedEventArgs e)
{
// ...
}
}
現在我可以在XAML中設置Binding
<local:MyButton MyStorage="{Binding MyProperty.MySubProperty}"/>
這解決了我的問題。 但我仍然很好奇如何在沒有XAML的情況下進行此綁定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.