如何在wpf中使用MVVM处理ComboBox的SelectionChanged事件? [英] How to handle the SelectionChanged event of ComboBox with MVVM in wpf?

查看:1043
本文介绍了如何在wpf中使用MVVM处理ComboBox的SelectionChanged事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用MVVM模式引发/处理WPF ComboBoxSelectionChanged事件?
请详细说明我是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解决方案:

ComboBoxItemsSourceSelectedItem属性绑定到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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆