你如何处理MVVM中的ComboBox SelectionChanged?

Edw*_*uay 31 wpf events mvvm attachedbehaviors

对于那些使用纯MVVM的人来说,如何在不回复代码的情况下处理ComboBox SelectionChanged事件?

我尝试了例如AttachedBehaviors,但不支持Event ="SelectedChanged":

<ComboBox>
    <ComboBoxItem Content="Test1">
        <c:CommandBehaviorCollection.Behaviors>
            <c:BehaviorBinding Event="SelectionChanged" 
                               Command="{Binding SelectedChanged}"
                               CommandParameter="MainBorder123"/>
        </c:CommandBehaviorCollection.Behaviors>
    </ComboBoxItem>
    <ComboBoxItem Content="Test2"/>
    <ComboBoxItem Content="Test3"/>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

fab*_*ien 68

这篇文章很老了,但是因为我遇到了同样的问题.以下是我如何解决它(使用框架4.0):想法是使用System.Windows.Interactivity.

在XAML中:

<ComboBox ItemsSource="{Binding Items}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding SelectionChangedCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

然后,您只需在viewmodel中实现SelectionChangedCommand.

  • 在添加对System.Windows.Interactivity的引用之后,您需要将此名称空间添加到XAML标头中:xmlxml:i =“ http://schemas.microsoft.com/expression/2010/interactivity” 。 (4认同)
  • 对于 .net core,您将需要这个 nuget:`https://github.com/Microsoft/XamlBehaviorsWpf`。将以下内容添加到窗口布局 xml 的 `&lt;Window/&gt;` -&gt; `xmlns:i="http://schemas.microsoft.com/xaml/behaviors"` 详细信息:[此处](https:// /devblogs.microsoft.com/dotnet/open-source-xaml-behaviors-for-wpf/) (3认同)
  • 如何在不给它命名的情况下绑定`ComboBox`的`SelectedItem`或`SelectedValue`? (2认同)

HAd*_*des 26

我不确定你所追求的是否可能,但我这样做的方法是简单地将SelectedItem绑定到视图模型上的属性.然后在属性设置器中,我调用我想要发生的任何自定义代码,即根据规则设置其他属性.如果我需要将所选项绑定到对象以及(对于要更新的​​其他绑定控件),我也会在setter中设置它并发送通知.

  • 我发现这是一种令人难以置信的痛苦方式.对于简单的应用程序,执行此操作而不是命令很容易.但它很快变得笨拙.属性应保存数据,而不是执行操作.它打破了异步,并且使调试更加困难,因为Visual Studio默认会跳过属性设置器/ getter. (6认同)

Pet*_*ter 3

您可以使用数据触发器来触发不同 UI 元素上的事件,例如“启用/禁用,或可见/不可见”

如果您希望所选元素显示其他 UI 元素中的对象数据,则可以使用数据绑定并将 UI 数据显示元素的数据上下文设置为绑定到组合框中当前选定的项目。