首页 > 解决方案 > 处理 SelectionChanged 和 MouseDown

问题描述

我有一个使用 MVVM 的 WPF 应用程序,该应用程序包含 2 ListBoxes。由于我使用的是 MVVM,因此我在我的 XAML 中使用 EventTriggers,如下所示:

<ListBox x:Name="ListBox1" 
                 Grid.Row="0"
             ItemsSource="{Binding EventLogs, UpdateSourceTrigger=PropertyChanged}"
             SelectedItem="{Binding SelectedLocalLog, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
             ScrollViewer.HorizontalScrollBarVisibility="Hidden"
             ScrollViewer.VerticalScrollBarVisibility="Auto"
             SelectionMode="Single">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:InvokeCommandAction Command="{Binding LoadEventLogEntriesCommand}" CommandParameter="{Binding ElementName=ListBox1, Path=SelectedItem}" />
                </i:EventTrigger>
                <i:EventTrigger EventName="MouseDown">
                    <i:InvokeCommandAction Command="{Binding LoadEventLogEntriesCommand}" CommandParameter="{Binding ElementName=ListBox1, Path=SelectedItem}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
 </ListBox>

我的 ViewModel 中的代码:

this.LoadEventLogEntriesCommand = new DelegateCommand(this.LoadLog);

private void LoadLog()
{
        this.worker = new BackgroundWorker();
        this.worker.ProgressChanged += new ProgressChangedEventHandler(this.UpdateProgress);
        this.worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.RunWorkerCompleted);
        this.worker.WorkerReportsProgress = true;
        this.worker.WorkerSupportsCancellation = true;
        this.worker.DoWork += new DoWorkEventHandler(this.ReadLog);

        // read entries
        if (worker.IsBusy != true)
        {
            worker.RunWorkerAsync(this);
        }
}

当我单击 中的行时ListBox,我触发了事件SelectionChanged,因此LoadLog()在我的 ViewModel 中调用了我的方法,该方法创建了一个BackgroundWorker来做一些事情。但是,我知道这也调用了我的MouseDown事件,因此这个方法被调用了两次,因为我将 EventTriggers 绑定到我的 ViewModel 中的同一命令。

我想要的是我已经单击 ListBox 中的一行之后,我想再次单击同一行并触发和事件来运行我的命令。我怎样才能做到这一点?

标签: c#wpfeventsmvvm

解决方案


您可以尝试处理MouseUp事件(仅):

<i:EventTrigger EventName="MouseUp">
    <i:InvokeCommandAction Command="{Binding LoadEventLogEntriesCommand}" CommandParameter="{Binding ElementName=ListBox1, Path=SelectedItem}" />
</i:EventTrigger>

推荐阅读