带有MVVM和CommandParameter的ListBox SelectionChanged事件

Van*_*nel 1 c# wpf xaml listbox mvvm

我正在使用WPF,C#和.NET Framework 4.6.1开发MVVM应用程序.

我正在尝试ListBox SelectionChanged使用MVVM 实现事件.要做到这一点,我做到了这一点:

安装nuget包:PM> Install-Package System.Windows.Interactivity.WPF.
添加xmlns:interactivity="http://schemas.microsoft.com/expression/2010/interactivity"xaml.
将此代码添加到我ListBox的xaml中:

<ListBox x:Name="listBoxTrzType" Grid.Column="1" Margin="10,0,25,0" VerticalAlignment="Center" Height="25" ItemsSource="{Binding TrzTypes}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Name}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <interactivity:Interaction.Triggers>
        <interactivity:EventTrigger EventName="SelectionChanged">
            <interactivity:InvokeCommandAction Command="{Binding ListBoxTrzTypeSelectionChanged}"
                                                CommandParameter="{Binding ElementName=listBoxTrzType, Path=SelectedItem}">
            </interactivity:InvokeCommandAction>
        </interactivity:EventTrigger>
    </interactivity:Interaction.Triggers>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

在ViewModel上我有:

public ICommand ListBoxTrzTypeSelectionChanged
{
    get { return new DelegateCommand(TrzTypeSelectionChanged); }
}

private void TrzTypeSelectionChanged()
{
    throw new NotImplementedException();
}
Run Code Online (Sandbox Code Playgroud)

DelegateCommand班级:

public class DelegateCommand : ICommand
{
    private readonly Action _action;

    public DelegateCommand(Action action)
    {
        _action = action;
    }

    public void Execute(object parameter)
    {
        _action();
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

#pragma warning disable 67
    public event EventHandler CanExecuteChanged { add { } remove { } }
#pragma warning restore 67
}
Run Code Online (Sandbox Code Playgroud)

但我的问题是我不知道如何传递CommandParameter="{Binding ElementName=listBoxTrzType, Path=SelectedItem}"给我private void TrzTypeSelectionChanged().

我一直在互联网上搜索很多,但我没有找到任何例子(只有例子CanExecute).

如何修改我的ViewModel类来访问SelectedItem参数?

Den*_*nis 6

实际上,对这样的任务使用交互行为是过度的.
你甚至不需要这里的命令.将SelectedItem属性添加到视图模型并监听属性更改就足够了:

public class SomeVm : INotifyPropertyChanged
{
    // INPC implementation is omitted

    public IEnumerable<SomeType> Items { get; }
    public SomeType SelectedItem
    {
        get { return selectedItem; }
        set
        {
            if (selectedItem != value)
            {
                selectedItem = value;
                OnPropertyChanged();
                // do what you want, when property changes
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

XAML:

<ListBox ItemsSource="{Binding Items}"
         SelectedItem="{Binding SelectedItem}"
         DisplayMemberPath="Name"/>
Run Code Online (Sandbox Code Playgroud)