WPF ComboBox项(ItemsSource绑定)不可见

时间:2018-12-18 03:11:08

标签: c# wpf xaml binding

我正在尝试将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>

问题

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

enter image description here

输出窗口中的错误

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

1 个答案:

答案 0 :(得分:1)

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

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

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