0
        <ListBox Grid.Row="1" ItemsSource="{Binding Source}" SelectedItem="{Binding SelectedItem,Mode=TwoWay}" DisplayMemberPath="Name">
        <ListBox.ItemContainerStyle>
            <Style>
                <EventSetter Event="ListBoxItem.MouseDoubleClick" Handler="DoubleClick" />
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

这就是它现在的工作方式。如果我想将每个 ListBoxItem 的 DoubleClick 事件绑定到一个 RelayCommand 应该怎么做?

4

2 回答 2

0

这就是我使用 MVVMLight EventToCommand 功能的方式。

如果你有一个双击事件挂钩。如果这不可用,请使用(预览)mousedown 并检查命令 args 中的 clickCount。ClickCount 为 2 对应于双击。

请注意:我有自己的 RelayCommand 实现。MVMMLight 工具包中的那个可能看起来不同。

XAML:

<interactivity:Interaction.Triggers>
    <interactivity:EventTrigger EventName="MouseDown">
        <mvvmLight:EventToCommand PassEventArgsToCommand="True" Command="{Binding MouseDownCommand}"></mvvmLight:EventToCommand>
    </interactivity:EventTrigger>
</interactivity:Interaction.Triggers>

视图模型:

public ICommand MouseDownCommand
{
  get
  {
    if (_mouseDownCommand == null)
    {
      _mouseDownCommand = new RelayCommand(x => MouseDown(x as MouseButtonEventArgs));
    }
    return _mouseDownCommand;
  }
}

private void MouseDown(MouseButtonEventArgs e)
{
  if (e.ClickCount == 2)
  {
    // do stuff
  }
}
于 2012-01-13T11:18:22.043 回答
-2

做到这一点的最好方法是使用以代码隐藏编写的普通事件处理程序。如果需要,这可以传递给模型或视图模型上的方法或命令。

使用 EventToCommand 行为之类的技巧只会让您付出更复杂的 XAML 的代价,而且您会泄漏内存的风险很高。(发生这种情况是因为 EventToCommand 监听 CanExecuteChanged 事件,即使它不应该监听。)

于 2012-01-13T09:30:46.227 回答