首页 > 解决方案 > ListViewItem EventTrigger 未触发 WPF

问题描述

我有在 xaml ListViewItems 中定义的 ListView。我正在尝试通过 Microsoft.Xaml.Behaviors.Wpf 将命令绑定到 PreviewMouseLeftButtonDown 单击事件上的 LisdtViewItem,但它不起作用。

Xml代码:

                    <ListView x:Name="SideMenu"
                              ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                              BorderThickness="0 0 1 0"
                              ItemContainerStyle="{StaticResource MenuItem}">
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Vertical" VerticalAlignment="Stretch" ToolTip="{Binding ToolTip}">
                                    <Image Source="{Binding ImageAddress}" Style="{StaticResource MenuIcon}"/>
                                </StackPanel>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                        <ListViewItem IsSelected="True">
                            <Image Source="../Icons/TestPlan.png" Style="{StaticResource MenuIcon}"/>
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
                                    <i:InvokeCommandAction Command="{Binding TestingCommand}"/>
                                </i:EventTrigger>
                            </i:Interaction.Triggers>
                        </ListViewItem>

视图模型代码:


    public sealed class SideMenuControlViewModel
    {
        public ICommand GetOddsCommand { get; set; }

        public SideMenuControlViewModel()
        {
            GetOddsCommand = new RelayCommand(o => GetOdds());
        }

        public ICommand TestingCommand
        {
            get => new RelayCommand((s) => Test()); 
        }

        private void GetOdds()
        {

        }

        private void Test()
        {
            int a = 5;
            int b = a + a;
        }
    }

另外,我尝试在图像和边框内添加事件触发器,但这也无济于事......

标签: c#wpf

解决方案


问题是我使用 ICommand 不是来自 System.Windows.Input 只是从教程中复制它......我只是改变了我的 RelayCommand 类继承和命令绑定开始照常工作


    public sealed class RelayCommand : ICommand
    {
        private readonly Action _action;

        public event EventHandler CanExecuteChanged = (sender, e) => { };

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

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

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

推荐阅读