我需要将文本块(或者可能是图像 - 总之,都是用户控件)的双击事件绑定到 ViewModel 中的一个命令上。
TextBlock.InputBindings 似乎无法正确地绑定到我的命令,请帮忙解决一下?
我需要将文本块(或者可能是图像 - 总之,都是用户控件)的双击事件绑定到 ViewModel 中的一个命令上。
TextBlock.InputBindings 似乎无法正确地绑定到我的命令,请帮忙解决一下?
<Button>
<Button.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="YourCommand" />
</Button.InputBindings>
</Button>
http://thejoyofcode.com/Invoking_a_Command_on_a_Double_Click_or_other_Mouse_Gesture.aspx
很简单,我们可以使用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"
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>
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
}
我曾经也遇到过类似的问题,需要将listview的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" >
codebehind
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
doubleClickButton.Command.Execute(null);
}
虽然不是很直观,但实际上很简单且有效。
ICommand
来实现:<MouseBinding Gesture="LeftDoubleClick" Command="{Binding YourCommand}" />
。 - Sheridan