2012-02-07 56 views
1

我想將我的類的列表綁定到WPF中的CombpBox。我認爲這應該很簡單。將簡單列表<myClass>綁定到Combobox

我試過的代碼,但它不工作:

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" /> 

我做錯了嗎?上的DataContext和ItemsSource時的區別

+0

這兩個答案都正確提交的Piotr Auguscik和blindmeis:comboBox1.DisplayMemberPath = 「值」; comboBox1.SelectedValuePath =「Id」;此外,還必須更改屬性:public class SimpleClass { public string Id {get;組; } public string Value {get;組; } } – Goxy 2012-02-07 13:49:31

回答

2

應該

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

在後面的代碼不能分配通過設置字符串它是一個稍微複雜一些的結合。在這種情況下,DisplayMemberPathSelectedValuePath只需要屬性名稱,而不是綁定。

+0

是的,你是對的。它應該只是字段的名稱 – Goxy 2012-02-07 13:42:38

1
comboBox1.ItemsSource = ListData; 

更多信息可以讀取here

+0

它與xaml中的綁定完成 – blindmeis 2012-02-07 12:45:20

0

應該comboBox.ItemsSource = ListData;

或者在XAML

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

帶有「SelectedValue」的那部分沒有任何意義。 – 2012-02-07 10:56:50

+0

看到上面的評論 – Goxy 2012-02-07 13:44:18

1
<ComboBox ItemsSource="{Binding }" /> 
+0

它可以寫成ItemsSource =「{Binding}」 – Goxy 2012-02-07 13:43:14

0

你可以綁定到公共屬性,所以你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; } 
} 
+0

是的,我錯過了在我的課,謝謝 – Goxy 2012-02-07 13:43:41