如何将WPF中的命令绑定到控件的双击事件处理程序?

blu*_*bit 62 data-binding wpf command double-click mvvm

我需要将文本块的双击事件(或者可能是图像 - 无论哪种方式,它的用户控件)绑定到我的ViewModel中的命令.

TextBlock.InputBindings似乎没有正确绑定到我的命令,任何帮助?

小智 245

<Button>
<Button.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="YourCommand" />
</Button.InputBindings>
</Button>
Run Code Online (Sandbox Code Playgroud)

http://thejoyofcode.com/Invoking_a_Command_on_a_Double_Click_or_other_Mouse_Gesture.aspx

  • +1就个人而言,我认为这个答案应该是标记为正确的答案.它不仅是迄今为止最简单的,而且还可以通过绑定到视图模型中的`ICommand`来与MVVM一起使用:`<MouseBinding Gesture ="LeftDoubleClick"Command ="{Binding YourCommand}"/>` (36认同)
  • 这只是一大堆令人敬畏的!它甚至适用于开箱即用的其他控件.例如<TextBlock.InputBindings> (5认同)
  • 凌乱的附加行为的好替代品:) (3认同)
  • 但是,你似乎无法在Style中使用它. (2认同)

Ken*_*art 10

尝试Marlon Grech的附加命令行为.

  • 我的项目中已经有三个辅助类.我只是希望WPF完全支持开发人员想要用它做的所有这些事情,但我想这会及时嘿.谢谢,这工作:) (3认同)
  • 我同意你的一般情绪 - 对于MVVM的支持并没有更多地融入WPF,这有点令人沮丧.大多数经验丰富的WPF开发人员已经建立了自己的辅助帮助程序的小库.如果您正在使用Silverlight,功能上的差距会更大! (2认同)
  • 不要单独链接到外部网站 - 请附上答案。如果该网站消失了,它就变得毫无用处。 (2认同)

Ada*_*dam 6

这很简单,让我们使用MVVM方式:我在这里使用MVVM Light,它易于学习和强大.

1.输出xmlns声明的以下行:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"  
xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;
                                   assembly=GalaSoft.MvvmLight.Extras.WPF4"
Run Code Online (Sandbox Code Playgroud)

2.像这样定义你的文本块:

<textBlock text="Text with event">
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="MouseDoubleClick">
         <GalaSoft_MvvmLight_Command:EventToCommand 
                             Command="{Binding Edit_Command}"/>
      </i:EventTrigger>
   </i:Interaction.Triggers>
</textBlock>
Run Code Online (Sandbox Code Playgroud)

3.然后在viewmodel中编写命令代码!!!

ViewModel1.cs

Public RelayCommand Edit_Command
{
   get;
   private set;
}

Public ViewModel1()
{
   Edit_Command=new RelayCommand(()=>execute_me());
}

public void execute_me()
{
   //write your code here
}
Run Code Online (Sandbox Code Playgroud)

我希望这对你有用,因为我在Real ERP应用程序中使用它


小智 2

我也遇到了类似的问题,我需要将列表视图的 MouseDoubleClick 事件绑定到 ViewModel 中的命令。

我提出的最简单的解决方案是放置一个具有所需命令绑定的虚拟按钮,并在 MouseDoubleClick 事件的事件处理程序中调用按钮命令的 Execute 方法。

.xaml

 <Button Visibility="Collapsed" Name="doubleClickButton" Command="{Binding Path=CommandShowCompanyCards}"></Button>
                <ListView  MouseDoubleClick="ListView_MouseDoubleClick" SelectedItem="{Binding Path=SelectedCompany, UpdateSourceTrigger=PropertyChanged}" BorderThickness="0" Margin="0,10,0,0" ItemsSource="{Binding Path=CompanyList, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" HorizontalContentAlignment="Stretch" >
Run Code Online (Sandbox Code Playgroud)

代码隐藏

     private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
            {
                doubleClickButton.Command.Execute(null);
            }
Run Code Online (Sandbox Code Playgroud)

它并不简单,但非常简单并且有效。