我想將我的類的列表綁定到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時的區別
這兩個答案都正確提交的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