WPF EventToCommand 将事件转化为命令

由 帅木 发布

WPF EventToCommand 将事件转化为命令

1.前台XAML

<ListBox Style="{DynamicResource ListBoxTransparent}" HorizontalContentAlignment="Center" ItemsSource="{Binding Datas}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical" Margin="0,10,0,10">
                <Image Width="40" Height="40" Source="{Binding ImgPath}"/>
                <TextBlock Margin="6,0,0,0" Text="{Binding Name}" HorizontalAlignment="Center"/>
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="MouseLeftButtonUp">
                        <i:InvokeCommandAction Command="{Binding DataContext.LeftBarMenuSelectionChangedCommand, RelativeSource={RelativeSource AncestorType=ListBox}}"
                                   CommandParameter="{Binding}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding LeftBarMenuSelectionChangedCommand}"
                                   CommandParameter="{Binding SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ListBox>


ListBox.Item中使用 {Binding DataContext.LeftBarMenuSelectionChangedCommand, RelativeSource={RelativeSource AncestorType=ListBox}} 来绑定ListBox的DataContext中的Command,如果不指定绑定源的话绑定的会是LstBox.Item中的Command。

ListBox使用 {Binding SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}} 来绑定当前选中的项。
需要引用命名空间: xmlns:i="http://schemas.microsoft.com/xaml/behaviors"。

2.后台C#代码

 [RelayCommand]
 private void LeftBarMenuSelectionChanged(object obj)
 {
     if (obj is LeftBarDataModel data)
     {
         ShowMsg(data.Name);
     }
 }

C#代码中使用了CommunityToolkit.Mvvm。


0条评论

评论已关闭