【发布时间】:2011-11-01 17:34:11
【问题描述】:
我有一个 WPF ComboBox,并且正在使用 MVVM 来绑定 ItemsSource 和 SelectedItem 属性。基本上我想要做的是当用户选择组合框中的特定项目时,组合框会选择不同的项目。
<ComboBox ItemsSource="{Binding TestComboItemsSource}" SelectedItem="{Binding TestComboItemsSourceSelected}"></ComboBox>
出于演示目的,我还有一个按钮来更新 SelectedItem。
<Button Command="{Binding DoStuffCommand}">Do stuff</Button>
我的 viewModel 中有这个:
public ObservableCollection<string> TestComboItemsSource { get; private set; }
public MyConstructor()
{
TestComboItemsSource = new ObservableCollection<string>(new []{ "items", "all", "umbrella", "watch", "coat" });
}
private string _testComboItemsSourceSelected;
public string TestComboItemsSourceSelected
{
get { return _testComboItemsSourceSelected; }
set
{
if (value == "all")
{
TestComboItemsSourceSelected = "items";
return;
}
_testComboItemsSourceSelected = value;
PropertyChanged(this, new PropertyChangedEventArgs(TestComboItemsSourceSelected))
}
}
private ICommand _doStuffCommand;
public ICommand DoStuffCommand
{
get
{
return _doStuffCommand ?? (_doStuffCommand = new RelayCommand(p =>
{
TestComboItemsSourceSelected = "items";
})); }
}
好的,所以我想让 ComboBox 在用户选择项目“全部”时选择项目“项目”。 使用该按钮,我可以更新组合框的 SelectedItem,我可以在 UI 中看到这一点
我有类似的逻辑来更新我的 TestComboItemsSourceSelected 属性设置器中的 viewModel。如果用户选择“全部”,则将 SelectedItem 设置为“项目”。因此,在代码方面,viewmodel 属性会发生变化,但由于某种原因,这不会反映在 UI 中。我错过了什么吗?我的实现方式是否有某种副作用?
【问题讨论】:
标签: wpf combobox selecteditem two-way-binding