gpt4 book ai didi

c# - 调试/断点为什么 WPF BindingExpression 为空

转载 作者:太空宇宙 更新时间:2023-11-03 20:11:04 25 4
gpt4 key购买 nike

我有一个 WPF CustomControl,它有一个名为 SelectedRange 的依赖属性。

在 XAML 中的应用程序中,绑定(bind)设置如下:

SelectedRange="{Binding Source={StaticResource ResourceKey=MainWindow},
Path=GlobalXRange, Mode=TwoWay}"

我在代码中发现 BindingExpression 正在被覆盖(设置为空)。我可以用这段代码确定这一点:

public IRange SelectedRange
{
get { return (IRange)GetValue(SelectedRangeProperty); }
set
{
SetValue(SelectedRangeProperty, value);
Binding b = BindingOperations.GetBinding(this, SelectedRangeProperty);

BindingExpression be =
BindingOperations.GetBindingExpression(this, SelectedRangeProperty);
if (be == null)
{
Console.WriteLine("Binding expression is null!");
}
}
}

事实证明,应用程序启动后 BindingExpression 为 null。

所以我的问题是 - 我如何调试此 BindingExpression 为空的原因 - 例如它是在 XAML 中设置的,我如何才能找到它被设置为 null 的位置?

注意:输出控制台没有绑定(bind)错误

最佳答案

好的伙计们,感谢你们的帮助,我设法解决了这个问题。对于 future 的读者,我是这样做的。

此问题是由 DependencyProperty Precedence 引起的.绑定(bind)到 SelectedRange 的 TwoWay 位于 ItemTemplate 内,并被调用 SetValue(SelectedRangeProperty, value) 的自定义控件覆盖。

WPF 中的解决方案是使用SetCurrentValue(SelectedRangeProperty, value) .

但是,我正在编写一个跨平台控件(Silverlight、WinRT),而这种方法在 SL/WinRT 中不可用。为了解决方法,我必须创建一个绑定(bind)以通过代码中的代理设置 SelectedRangeProperty,例如

var binding = new Binding();
binding.Source = this;
binding.Path = new PropertyPath(SelectedRangeProxyProperty);
binding.Mode = BindingMode.TwoWay;
this.SetBinding(SelectedRangeProperty, binding);

感谢您的帮助,希望这对其他人有帮助!

关于c# - 调试/断点为什么 WPF BindingExpression 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20029968/

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