我试图将我的组合与列表绑定,但我什么都没得到
public MainWindow()
{
DataContext = this;
InitializeComponent();
List<item> list = new List<item>();
list.Add(new item() {id = 1,name = "stack"});
list.Add(new item() { id = 2, name = "overflow" });
comboBox.DataContext = list;
comboBox.SelectedIndex = 0;
}
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="22,14,0,0" VerticalAlignment="Top" Width="147"
ItemsSource="{Binding Path=list}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=id}" />
<Label Content=":" />
<Label Content="{Binding Path=name}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
答案 0 :(得分:0)
您正在设置comboBox.DataContext = list;
和DataContext=this
这不是MVVM的工作方式。此外,您永远不应该访问此背后的代码中的元素,这完全违反了MVVM原则。
相反,你应该做
public List<Item> List { get; set; }
public MainWindow()
{
InitializeComponent();
List = new List<Item>();
List.Add(new Item() { id = 1, name = "stack" });
List.Add(new Item() { id = 2, name = "overflow" });
DataContext = this; //This is the only place where you should set datacontext
}
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="22,14,0,0"
VerticalAlignment="Top" Width="147" ItemsSource="{Binding List}" SelectedIndex=0 >