首页 > 解决方案 > 通过 System.Windows.Interactivity 中的 EventTrigger 实现 MVVM Light、Mahapps Metro 和 EventToCommand

问题描述

我要疯了:我有一个使用 Mahapps.Metro 和 MVVMLight 的应用程序。基本上大多数事情都可以,直到您尝试使用 Interaction.Triggers。

我通常会遇到类似的错误

Cannot add instance of type 'EventToCommand' to a collection of type 'TriggerActionCollection'. Only items of type 'T' are allowed.

重现此问题的一种方法是通过我在网上找到的 repo: https ://github.com/mike-schulze/mahapps-mvvmlight-setup (抱歉,mike 劫持了)并将 Metro SplitButton 添加到视图模型:

<Controls:SplitButton ItemsSource="{Binding MyList}" Grid.Column="1" Grid.Row="1">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <cmd:EventToCommand 
                                    Command="{Binding Mode=TwoWay, Path=SelectionChangedCommand}" 
                                    PassEventArgsToCommand="True"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Controls:SplitButton>

而 MyList 是

        public List<string> MyList
        {
            get
            {
                List<string> theList = new List<string>();
                theList.Add("Hello");
                theList.Add("World");
                return theList;
            }
        }

我不确定 App.config 中有多少不同的命名空间、硬编码的交互版本,或者我曾经尝试过什么。

有没有人使用 Mahapps Metro(版本不太旧)和 MVVM Light 以及 EventToCommand 的东西的工作示例?

我认为我的问题与 Metro 的更新有关——他们现在使用的是行为而不是交互性。我正在使用 Interactivity dll 版本 4.5.0.0。但即使是我上面提到的旧 git 也显示了问题......而且我找不到有效的解决方案。

任何帮助是极大的赞赏。谢谢

标签: wpfmvvm-lightmahapps.metroeventtocommand

解决方案


您还需要为 System.Windows.Interactivity 添加命名空间。

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

因为 MVVMLight 使用了这个版本的 Interactivity。

<mah:MetroWindow x:Class="..."
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

                 ...

                 xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
                 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
                 xmlns:command="http://www.galasoft.ch/mvvmlight"

                 ...

                 DataContext="{Binding Main, Source={StaticResource Locator}}">

    ...
    
    <mah:SplitButton ItemsSource="{Binding MyList}">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <command:EventToCommand Command="{Binding Mode=TwoWay, Path=SelectionChangedCommand}" PassEventArgsToCommand="True" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </mah:SplitButton>

    ...

</mah:MetroWindow>

推荐阅读