gpt4 book ai didi

c# - 在代码隐藏中绑定(bind)到嵌套对象中的属性

转载 作者:行者123 更新时间:2023-11-30 17:21:11 26 4
gpt4 key购买 nike

嵌套的 ViewModel 设置为 MainWindow DataContext:

var mainWindow = new MainWindow();
mainWindow.Show();
mainWindow.DataContext = new
{
MyProperty = new
{
MySubProperty = "Hello"
}
}

在 XAML 中很容易绑定(bind)到 MySubProperty:

<Button Content="{Binding MyProperty.MySubProperty}"/>

如何在代码隐藏中执行此绑定(bind)?

// 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 只是一个示例,但这将是一个开始。在我原来的场景中,我没有有用的依赖属性。如果此类绑定(bind)需要 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)
{
// ...
}
}

编辑:

为了在代码隐藏中绑定(bind)一些东西,你可以使用:

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);

关于c# - 在代码隐藏中绑定(bind)到嵌套对象中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3688912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com