绑定简单列表<;myClass>;到组合框

本文关键字:组合 gt myClass 简单 lt 绑定 列表 | 更新日期: 2023-09-27 18:23:49

我想将类的List绑定到WPF中的CombpBox。我觉得应该很简单。

我尝试了代码,但它不起作用:

    public MainWindow()
    {
        InitializeComponent();
        List<SimpleClass> ListData = new List<SimpleClass>();
        ListData.Add(new SimpleClass { Id = "1", Value = "One" });
        ListData.Add(new SimpleClass { Id = "2", Value = "Two" });
        ListData.Add(new SimpleClass { Id = "3", Value = "Three" });
        ListData.Add(new SimpleClass { Id = "4", Value = "Four" });
        ListData.Add(new SimpleClass { Id = "5", Value = "Five" });

        comboBox1.DataContext = ListData;
        comboBox1.DisplayMemberPath = "{Binding Path=Value}";
        comboBox1.SelectedValuePath = "{Binding Path=Id}";

    }
}
public class SimpleClass
{
    public string Id;
    public string Value;
}

XAML如下

 <ComboBox Height="23" HorizontalAlignment="Left" Margin="221,107,0,0" Name="comboBox1" ItemsSource="{Binding}" VerticalAlignment="Top" Width="120" />

我做错了什么?

绑定简单列表<;myClass>;到组合框

应该是

comboBox1.DisplayMemberPath = "Value";
    comboBox1.SelectedValuePath = "Id";

在代码隐藏中,您不能通过设置字符串来分配绑定,这有点复杂。在这种情况下,DisplayMemberPathSelectedValuePath只需要属性名称,而不需要绑定。

comboBox1.ItemsSource = ListData;

有关DataContext和ItemsSource之间差异的更多信息,可以在此处阅读。

<ComboBox ItemsSource="{Binding }" />

应该是comboBox.ItemsSource = ListData;

或在XAML 中

<ComboBox ItemsSource="{Binding Path=ListData}"
                  DisplayMemberPath="Value"
                  SelectedValuePath="Id"
                  SelectedValue="{Binding Path=ListData}" />

您可以直接绑定到公共属性,所以您的simpleclass是不对的。和Piotr提到的一样,您必须为Displaymemberpath设置简单的字符串。

工作示例

    public MainWindow()
    {
        InitializeComponent();
        List<SimpleClass> ListData = new List<SimpleClass>();
        ListData.Add(new SimpleClass { Id = "1", Value = "One" });
        ListData.Add(new SimpleClass { Id = "2", Value = "Two" });
        ListData.Add(new SimpleClass { Id = "3", Value = "Three" });
        ListData.Add(new SimpleClass { Id = "4", Value = "Four" });
        ListData.Add(new SimpleClass { Id = "5", Value = "Five" });

        comboBox1.DataContext = ListData;
        comboBox1.DisplayMemberPath = "Value";
        comboBox1.SelectedValuePath = "Id";
    }
public class SimpleClass
{
    public string Id  { get; set; }
    public string Value { get; set; }
}