Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListBox.DisplayMemberPath doesn't work as expected. How can I debug this?

    <ListBox ItemsSource="{Binding Path=Commands}" DisplayMemberPath="Name"/>

DisplayMemberPath doesn't work, and ListBox shows default ToString result of the Commands collection members. Is it possible to debug this, for example, by printing some information to Output window?

Visual Studio 2010, WPF application project. Binding is successful, and I see all members of the Commandscollection. But display is wrong.

Additional information. If I change Path=Commands to non-existing Path=Commands1, I see error messages in the Output window. But there is no any information about error in DisplayMemberPath.

like image 987
Alex F Avatar asked Jun 05 '26 13:06

Alex F


1 Answers

One of the clearer/cleaner ways I've come across for debugging binding errors in WPF is often linked (but using an older, broken link) and can currently be found here: http://www.zagstudio.com/blog/486#.UhyT8fNwbs0

Specifically, the approach that uses a debugging feature introduced in .Net 3.5, using the attached property PresentationTraceSources.TraceLevel and allows you to specify a particular trace level to investigate your binding issues.

Summarising here:

You add the following namespace:

<Window
<!-- Window Code -->
xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase"
/>

And in your binding expression, set the attached property. In my example, I'm using a list of Cars objects with a Name property, and have incorrectly listed the DisplayMemberPath as Names:

<ListBox ItemsSource="{Binding Path=Cars, diagnostics:PresentationTraceSources.TraceLevel=High}" DisplayMemberPath="Names" />

This results in the following message in the Output window (occurring multiple times, one for each failed binding):

System.Windows.Data Error: 40 : BindingExpression path error: 'Names' property not found on 'object' ''Car' (HashCode=59988153)'. BindingExpression:Path=Names; DataItem='Car' (HashCode=59988153); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

The whole link is worth a read, but that's the gist of a particular technique I had success with (in case the link dies).

like image 137
Chris Avatar answered Jun 08 '26 04:06

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!