wpf ObservableCollection 中的 SelectedItem
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16761250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SelectedItem in ObservableCollection
提问by BBH1023
I have:
我有:
<DataTemplate x:Name="_ComboBoxTemplate" x:Key="_ComboBoxTemplate">
<StackPanel Orientation="Horizontal">
<StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<TextBlock VerticalAlignment="Center" Text="{Binding}" FontSize="24"/>
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
<ComboBox x:Name="_criteria" ItemTemplate="{StaticResource _ComboBoxTemplate}" ItemsSource="{Binding}"/>
In the code behind:
在后面的代码中:
this.DataContext = new string[] { "0", "1", "2", "3", "4", "5" };
How do I get it so that the default SelectedItemin ComboBoxis 5?
我如何得到它使默认SelectedItem的ComboBox是5?
回答by Damir Arh
Create a class containing both your list of items and the selected item:
创建一个包含您的项目列表和所选项目的类:
public class ViewModel
{
public string[] Items { get; set; }
public string SelectedItem { get; set; }
}
Initialize it in code behind and set it as DataContext:
在后面的代码中初始化它并将其设置为DataContext:
DataContext = new ViewModel
{
Items = new string[] { "0", "1", "2", "3", "4", "5" },
SelectedItem = "5"
}
Now bind both properties to your ComboBox:
现在将这两个属性绑定到您的ComboBox:
<ComboBox x:Name="_criteria"
ItemTemplate="{StaticResource _ComboBoxTemplate}"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}"/>
If you set two way binding for SelectedItemthe value in DataContextwill even update automatically when the user changes it.
如果您为SelectedItem值设置了双向绑定,DataContext当用户更改它时甚至会自动更新。
Why did you mention ObservableCollectionin the title?
为什么ObservableCollection在标题中提到?
回答by gjulianm
Just after you set the DataContext, set _criteria.SelectedIndex = _criteria.ItemsSource.Count - 1.
在设置 DataContext 之后,设置_criteria.SelectedIndex = _criteria.ItemsSource.Count - 1.
But I'd go with another workaround: reverse the order of the array. That is, this.DataContext = new string[] { "5", "4", ... }. "5" would be the first item and you'd keep the order of the list without any other hacks.
但我会采用另一种解决方法:颠倒数组的顺序。也就是说,this.DataContext = new string[] { "5", "4", ... }。“5”将是第一项,您将保持列表的顺序,而无需任何其他技巧。

