如何在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屋!