简体   繁体   English

WPF ComboBox项(ItemsSource绑定)不可见

[英]WPF ComboBox items (ItemsSource binding) are not visible

I am trying to bind List<MyClass> to ComboBox . 我正在尝试将List<MyClass>绑定到ComboBox Following is simple code which I implemented : 以下是我实现的简单代码:

C# C#

cmbList.ItemsSource = DbMain.GetNameList();

XAML 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. DbMain.GetNameList()中检索List<MyClass>值,并在ComboBox绑定,但这些值不可见。 When I perfrom SelectionChanged , I can access SelectedItem as well. 当我从SelectionChanged ,我也可以访问SelectedItem 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. 通过使用此绑定表达式,您表示MyClass中有一个名为DisplayName属性 ,但是在运行时,由于没有这样的属性 -您将DisplayName定义为field ,这就是为什么在您的情况下它会失败的原因-因此ComboBox是显示空白项目。

<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. 与未处理的异常不同,这种绑定错误不会使应用程序崩溃,但是在调试时可以在输出窗口中找到它们的踪迹。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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