将简单的List <myclass>绑定到Combobox </myclass>

时间:2012-02-07 10:40:03

标签: c# .net wpf combobox

我想将我的类的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" />

我做错了什么?

5 个答案:

答案 0 :(得分:2)

应该是

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

在后面的代码中,你不能通过设置字符串来分配绑定它有点复杂。在这种情况下,DisplayMemberPathSelectedValuePath只期望属性名称,而不是绑定。

答案 1 :(得分:1)

comboBox1.ItemsSource = ListData;

有关DataContext和ItemsSource之间差异的更多信息,请参阅here

答案 2 :(得分:1)

<ComboBox ItemsSource="{Binding }" />

答案 3 :(得分:0)

应为comboBox.ItemsSource = ListData;

或者在XAML中

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

答案 4 :(得分:0)

您可以绑定到公共属性,因此您的简单类不正确。和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; }
}