Gaurang Dave
Gaurang Dave

Reputation: 4046

WPF ComboBox items (ItemsSource binding) are not visible

I am trying to bind List<MyClass> to ComboBox. Following is simple code which I implemented :

C#

cmbList.ItemsSource = DbMain.GetNameList();

XAML

<StackPanel Grid.Row="0" Orientation="Horizontal" >

    <TextBlock Text="Names:" Margin="5,0,5,0" VerticalAlignment="Center" Width="50" Visibility="Collapsed"/>

    <ComboBox x:Name="cmbList" Width="200" SelectionChanged="cmbList_SelectionChanged"
      DisplayMemberPath="DisplayName" SelectedValuePath="DisplayName" Foreground="Black"/>

</StackPanel>

Problem

Values of List<MyClass> are retrived from DbMain.GetNameList() and binding in ComboBox but those are not visible. When I perfrom SelectionChanged, I can access SelectedItem as well. Only issue is items are not visible.

enter image description here

Error in Output Window

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

Upvotes: 0

Views: 1523

Answers (1)

kennyzx
kennyzx

Reputation: 13003

By using this binding expression, you are stating that there is a property named DisplayName in MyClass, but at runtime, since there is no such property - you define DisplayName as a field, that is why it fails in your case - so the ComboBox is showing blank items.

<ComboBox x:Name="cmbList" 
  DisplayMemberPath="DisplayName"

Unlike unhandled exceptions, this kind of binding errors don't crash the application, but you can find their trace in the output window while debugging.

Upvotes: 1

Related Questions