gpt4 book ai didi

c# - 绑定(bind)命令丢失

转载 作者:行者123 更新时间:2023-12-03 10:26:30 26 4
gpt4 key购买 nike

我有一个控件 (a) 需要在其中显示/隐藏另一个控件 (b)

(a) 有:

1- 引用 (b)

2- (b) viewmodel 的依赖属性

(b) 有一个名为 的 View 模型的依赖属性查看型号 .

这是代码:
为一个)

如果我以这种方式创建所有 mi 绑定(bind)工作得很好,我的问题是,如果我有很多 (a) 实例,每个实例都工作,因为 b 是所有实例的同一个实例,因为它是一个静态属性。

public partial class a : UserControl
{
public a()
{

}

public bVM b
{
get { return (bVM)GetValue(bProperty); }
set { SetValue(bProperty, value); }
}

public static readonly DependencyProperty bProperty =
DependencyProperty.Register("b", typeof(bVM), typeof(a)), new PropertyMetadata(new bVM()));
}

现在,如果我在 (a) 构造函数中创建一个 bVM 实例,我的所有绑定(bind)都可以正常工作,除了 命令绑定(bind) .
public partial class a : UserControl
{
public a()
{
b = new bVM();
}

public bVM b
{
get { return (bVM)GetValue(bProperty); }
set { SetValue(bProperty, value); }
}

public static readonly DependencyProperty bProperty =
DependencyProperty.Register("b", typeof(bVM), typeof(a));
}

这是我在 (a) xaml 中对 (b) 的绑定(bind):
<local:b
x:Name="bName"
ViewModel="{Binding ElementName=ThisAControl,Path=b}"/>

这是我对命令丢失的绑定(bind)
<Button Content="Test" 
Command="{BindingElementName=ThisBControl,Path=ViewModel.ExitCommand }" />

为什么我的命令绑定(bind)丢失了第二种方式?
我做错了什么?

最佳答案

我同意@dymanoid 的评论,通常你不应该有 VM 的依赖属性。除了这个奇怪的实现之外,从技术上讲,绑定(bind)丢失的原因是因为在构造函数中你正在打破它:b = new bVM();要为依赖对象内的依赖属性设置值,您应该 SetCurrentValue方法,不会破坏任何绑定(bind)。SetCurrentValue(a.bProperty, new bVM());

MSDN: The SetCurrentValue method changes the effective value of the property, but existing triggers, data bindings, and styles will continue to work.

关于c# - 绑定(bind)命令丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633244/

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