繁体   English   中英

WPF ComboBox项(ItemsSource绑定)不可见

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

我正在尝试将List<MyClass>绑定到ComboBox 以下是我实现的简单代码:

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>

问题

DbMain.GetNameList()中检索List<MyClass>值,并在ComboBox绑定,但这些值不可见。 当我从SelectionChanged ,我也可以访问SelectedItem 唯一的问题是项目不可见。

在此处输入图片说明

输出窗口错误

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

通过使用此绑定表达式,您表示MyClass中有一个名为DisplayName属性 ,但是在运行时,由于没有这样的属性 -您将DisplayName定义为field ,这就是为什么在您的情况下它会失败的原因-因此ComboBox是显示空白项目。

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

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

暂无
暂无

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

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