我正试图从我的ViewModel中的ComboBox
中捕获所选项目的值。我确实得到了值,但出于某种原因,当我在IF语句中进行字符串比较以确定选择了哪个项目时,比较不起作用。
我错过了什么?
这是在ViewModel中捕获值的正确方法吗?
<ComboBox x:Name="comboBox"
SelectedItem="{Binding SelectedItemInFilter, UpdateSourceTrigger=PropertyChanged}>
<ComboBoxItem IsSelected="True">No Selection</ComboBoxItem>
<ComboBoxItem>Car</ComboBoxItem>
<ComboBoxItem>Truck</ComboBoxItem>
</ComboBox>
public class MyViewModel : ViewModelBase{
public string _selectedItemInFilter;
public string SelectedItemInFilter
{
get { return _selectedItemInFilter; }
set {
if (_selectedItemInFilter != value) {
_selectedItemInFilter = value;
ComboBoxChanged();
Console.WriteLine("SelectedItem: {0}", SelectedItemInFilter); // outputs the right item name
RaisePropertyChanged();
}
}
}
private void ComboBoxChanged()
{
if (SelectedItemInFilter.ToString() == "Car") {
Console.WriteLine("Do something with car...");
}
else {
Console.WriteLine("Is not Car...");
}
}
}
由于您显式添加了ComboBoxItems(而不是将ItemsSource设置或绑定到字符串集合),因此SelectedItem也是一个ComboBoxItem,而不是一个字符串。但是,您可以使用Content
和SelectedValue
绑定到所选项目的SelectedValuePath
字符串:
<ComboBox SelectedValue="{Binding SelectedItemInFilter}"
SelectedValuePath="Content">
<ComboBoxItem>No Selection</ComboBoxItem>
<ComboBoxItem>Car</ComboBoxItem>
<ComboBoxItem>Truck</ComboBoxItem>
</ComboBox>
更简单的是根本不使用ComboBoxItems:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
...
<ComboBox SelectedItem="{Binding SelectedItemInFilter}">
<sys:String>No Selection</sys:String>
<sys:String>Car</sys:String>
<sys:String>Truck</sys:String>
</ComboBox>
你弄错了,因为这些项目不是真正的字符串,如果你需要这样做,你可以做到以下几点:
public object _selectedItemInFilter;
public object SelectedItemInFilter
{
get
{
return _selectedItemInFilter;
}
set
{
if (_selectedItemInFilter != value)
{
_selectedItemInFilter = value;
ComboBoxChanged();
Console.WriteLine("SelectedItem: {0}", SelectedItemInFilter); // outputs the right item name
NotifyPropertyChanged("SelectedItemInFilter");
}
}
}
private void ComboBoxChanged()
{
if (((ComboBoxItem)SelectedItemInFilter).Content.ToString() == "Car")
{
Console.WriteLine("Do something with car...");
}
else
{
Console.WriteLine("Is not Car...");
}
}
将ObservableCollection
绑定到ComboBox
控件上并不是一样的。