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

查看:105
本文介绍了如何在 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天全站免登陆