WPF is a great toolset, and XAML databinding is very powerful, but I've often run into difficulty arising from its transparency: It can be tough to debug a databinding failure when no errors are thrown.
For example, I recently had to change a Style
declaration like this:
<DataGrid.RowStyle>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding TestProperty}" Value="False">
<Setter Property="DataGridRow.Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
Into this:
<DataGrid.Row开发者_如何学CStyle>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.TestProperty}" Value="False">
<Setter Property="DataGridRow.Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
In order for the DataGridRow property to be affected. It would be incredibly helpful to see, at design- or run-time, what the implications of binding to different sources and RelativeSource
s would be.
Do any such tools / techniques exist?
You can use PresentationTraceSources.TraceLevel
attached property on bindings to get detailed logging in the output during runtime.
In your case, it will look like this:
<DataGrid.RowStyle>
<Style>
<Style.Triggers>
<DataTrigger Value="False" Binding="{Binding DataContext.TestProperty,
RelativeSource={RelativeSource AncestorType=UserControl},
PresentationTraceSources.TraceLevel=High}">
<Setter Property="DataGridRow.Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
Bea Stollnitz has a very informative blog post about debugging WPF bindings.
If you are using Visual Studio 2010, you will need to update the default WPF trace setting.
If you run your application under the Visual Studio debugger, binding errors will be reported to the output window. These are very informative and should help you track down any errors.
Another option in Visual Studio 2010 is to put a breakpoint on the binding. This can easily be done by putting your clicking on the Binding keyword and pressing F9 to set the breakpoint. The Binding keyword will be highlighted in red. If a larger chunk of text is highlighted, it may be that the breakpoint does not work in the editor that you are using. If this happens, try right-clicking the file in Solution Explorer, select "Open with" and choose "Source Code (Text) Editor".
When you hit the breakpoint at runtime, you can examine it using the Locals debugger window and see what it is bound to.
精彩评论