简体   繁体   中英

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.

在此处输入图片说明

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')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM