Reputation: 21521
I have a WPF CustomControl with a depdendency property called SelectedRange.
In an application in XAML the binding is set like this:
SelectedRange="{Binding Source={StaticResource ResourceKey=MainWindow},
Path=GlobalXRange, Mode=TwoWay}"
I find in the code that the BindingExpression is getting overwritten (set to null). I can determine this with this code:
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!");
}
}
}
It turns out the BindingExpression is null after the application starts.
So my question is - how can I debug why this BindingExpression is null - e.g. it is set in XAML how can I find out where it is being set to null?
Note: There are no binding errors in the output console
Upvotes: 1
Views: 1280
Reputation: 21521
Ok guys, thanks to all your help I managed to solve this. For future readers here's how I did it.
This problem was caused by DependencyProperty Precedence. The TwoWay binding to SelectedRange was inside an ItemTemplate and was being overwritten by the Custom Control which was calling SetValue(SelectedRangeProperty, value).
The solution in WPF is to use SetCurrentValue(SelectedRangeProperty, value).
However, I am writing a cross-platform control (Silverlight, WinRT) and this method is not available in SL/WinRT. To workaround I had to create a binding to set the SelectedRangeProperty via a proxy in code, e.g.
var binding = new Binding();
binding.Source = this;
binding.Path = new PropertyPath(SelectedRangeProxyProperty);
binding.Mode = BindingMode.TwoWay;
this.SetBinding(SelectedRangeProperty, binding);
Thank you for all your help, hope this helps someone else!
Upvotes: 3
Reputation: 106826
You can enable tracing of the binding by adding the following to the binding expression:
PresentationTraceSources.TraceLevel=High
E.g.
{Binding
Source={StaticResource ResourceKey=MainWindow},
Path=GlobalXRange,
Mode=TwoWay,
PresentationTraceSources.TraceLevel=High}
You will then get additional information about the binding in the debug window.
Upvotes: 2