我有一个带有一个名为SelectedRange的depdendency属性的WPF CustomControl。
在XAML中的应用程序中,绑定设置如下:
SelectedRange="{Binding Source={StaticResource ResourceKey=MainWindow},
Path=GlobalXRange, Mode=TwoWay}"我在代码中发现BindingExpression正在被覆盖(设置为null)。我可以使用以下代码来确定这一点:
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为空。
所以我的问题是-我如何调试为什么这个BindingExpression为空-例如,它是在XAML中设置的,我如何找出它在哪里被设置为空?
注意:输出控制台中没有绑定错误
发布于 2013-11-17 22:30:30
好了,感谢你们的帮助,我终于解决了这个问题。对于未来的读者,我是如何做到这一点的。
这个问题是由DependencyProperty Precedence引起的。与SelectedRange的TwoWay绑定位于ItemTemplate内,并被调用SetValue(SelectedRangeProperty,value)的自定义控件覆盖。
WPF中的解决方案是使用SetCurrentValue(SelectedRangeProperty, value)。
然而,我正在编写一个跨平台的控件(Silverlight,WinRT),这种方法在SL/WinRT中不可用。为了解决这个问题,我不得不创建一个绑定来通过代码中的代理设置SelectedRangeProperty,例如
var binding = new Binding();
binding.Source = this;
binding.Path = new PropertyPath(SelectedRangeProxyProperty);
binding.Mode = BindingMode.TwoWay;
this.SetBinding(SelectedRangeProperty, binding);谢谢你的帮助,希望这对其他人有帮助!
发布于 2013-11-17 20:19:48
您可以通过将以下内容添加到绑定表达式来启用绑定跟踪:
PresentationTraceSources.TraceLevel=High例如。
{Binding
Source={StaticResource ResourceKey=MainWindow},
Path=GlobalXRange,
Mode=TwoWay,
PresentationTraceSources.TraceLevel=High}然后,您将在调试窗口中获得有关绑定的其他信息。
https://stackoverflow.com/questions/20029968
复制相似问题