gpt4 book ai didi

c# - 将一个控件绑定(bind)到另一个的 DataContext

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

我在 Window.xaml.cs 构造函数 (DataContext = WindowVM) 中使用 DataContext 将我的 wpf 窗口绑定(bind)到应用程序层类 (WindowVM.cs)。但是,我想将一个控件 (btnAdd) 绑定(bind)到 Window.xaml.cs 属性。因此,在 Window.xaml.cs 构造函数中,我添加了 this.btnAdd.DataContext。这是我要绑定(bind)到的 Window.xaml.cs 构造函数和属性 Button btnAdd:

    public Window()
{
InitializeComponent();
DataContext = WindowVM;
this.btnAdd.DataContext = this;
}

public RelayCommand Add
{
get
{
return _add == null ? _add= new RelayCommand(AddPP, CanAddPP) : _add;
}
set
{
OnPropertyChanged("Add");
}
}

Xaml 看起来像这样(类 PP 是 WindowVM 属性):

<TextBox Name="txtName" Text="{Binding PP.Name, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Name="txtSurname" Text="{Binding PP.Surname, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="{Binding Add}" Content="Add" ... />

并且 - 一切正常,但控制台输出如下:

BindingExpression path error: 'Add' property not found on 'object' ''WindowVM'...

在接下来的调用中,属性 Add 没有任何控制台输出错误。

现在我因为这个错误有点迷糊了。这个错误是因为第一个DataContext(到WindowVM),因为没有属性Add,但是找到了this.btnAdd.DataContext行属性Add,这就是原因它有效吗?

最佳答案

只需使用 RelativeSource 在 XAML 中设置 ButtonDataContext:

<Button Command="{Binding Add}" Content="Add" DataContext="{Binding Add, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" />

关于c# - 将一个控件绑定(bind)到另一个的 DataContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7366488/

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