如何在 wpf 中使用 MVVM 处理 ComboBox 的 SelectionChanged 事件? [英] How to handle the SelectionChanged event of ComboBox with MVVM in wpf?
问题描述
如何使用 MVVM 模式引发/处理 WPF 的 ComboBox
的 SelectionChanged
事件?
请详细解释我是WPF的新手.
How to raise / handle the SelectionChanged
event of WPF's ComboBox
using the MVVM pattern?
Explain in detail please I am new to WPF.
我想要的是在ComboBox
项选择改变时做一些操作.我怎样才能以 MVVM 的方式实现它?
What I want, is to do some operations when the ComboBox
item selection changed. How can I achieve it, in an MVVM way?
推荐答案
MVVM解决方案:
将 ComboBox
的 ItemsSource
和 SelectedItem
属性绑定到 ViewModel 中的属性:
Bind the ItemsSource
and SelectedItem
properties of the ComboBox
to properties in your ViewModel:
<ComboBox ItemsSource="{Binding MyItems}" SelectedItem="{Binding MySelectedItem}"/>
在 MainViewModel.cs 中:
In MainViewModel.cs:
public ObservableCollection<string> MyItems { get; set; }
private string _mySelectedItem;
public string MySelectedItem
{
get { return _mySelectedItem; }
set
{
// Some logic here
_mySelectedItem = value;
}
}
代码隐藏解决方案:
如果你不想使用MVVM,你可以添加使用这个:
If you don't want to use MVVM, you can add use this:
<ComboBox SelectionChanged="ComboBox_SelectionChanged" />
并在 MainWindow.xaml.cs 中添加:
And add this in MainWindow.xaml.cs:
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Some logic here
}
这篇关于如何在 wpf 中使用 MVVM 处理 ComboBox 的 SelectionChanged 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!