[英]How can I put default selected value in combobox in WPF MVVM
I have a combobox in WPF MVVM and I have 3 value in combobox.我在 WPF MVVM 中有一个 combobox,我在 combobox 中有 3 个值。 Values are: AB-All I want to "All" is default selection in combobox how can I do it?值是: AB-All 我想“全部”是 combobox 中的默认选择我该怎么做?
combobox in my xaml:我的 xaml 中的 combobox:
<ComboBox ItemsSource="{Binding Locations}" SelectedItem ="{Binding SelectedLocation}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding LocationFilterCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
Locations observable collection in my viewmodel:我的视图模型中的位置可观察集合:
private ObservableCollection<string> _locations;
public ObservableCollection<string> Locations
{
get { return _locations; }
set
{
_locations = value;
OnPropertyChanged("Locations");
}
}
Locations = new ObservableCollection<string>()
{
"All","A","B"
};
thank you for all your helps.感谢您的所有帮助。
View看法
<ComboBox
ItemsSource="{Binding Locations}"
SelectedItem="{Binding SelectedLocation}" />
ViewModel [using MVVMLight] ViewModel [使用 MVVMLight]
public class MainViewModel: ViewModelBase
{
public MainViewModel()
{
SelectedLocation = Locations.First();
}
public IEnumerable<string> Locations => new[] {"All", "A", "B"};
private string _selectedLocation;
public string SelectedLocation
{
get => _selectedLocation;
set
{
if (Set(nameof(SelectedLocation), ref _selectedLocation, value))
{
// Update location filter here
}
}
}
}
There's no need to use an ObservableCollection
for Locations
unless you plan to add more elements to the collection at some point.除非您计划在某个时候向集合中添加更多元素,否则无需对Locations
使用ObservableCollection
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.