如何在mvvm中绑定鼠标双击命令 [英] How to bind mousedouble click command in mvvm

查看:10
本文介绍了如何在mvvm中绑定鼠标双击命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有列表视图,我想在有人双击任何位置时显示新窗口.但我有 mvvm 应用程序,我不想在 xaml 文件后面的代码中有任何功能,如下所示:如何绑定一个命令来双击 DataGrid 中的一行 以及许多其他类似的示例.我想在视图模型文件中有方法并像这样绑定它:

I have listview and I want to have show new window when someone double click in any position. But I have mvvm application and I don't want to have any function in code behind of xaml file, like this: How to bind a Command to double-click on a row in DataGrid and many other samples like this. I want to have method in viewmodel file and bind it like this:

<ListView ... MouseDoubleClick="{Binding myfunction}"> 

谢谢

推荐答案

这是一个基于单击的列表中的项目触发命令(在 ViewModel 中)的方法的工作示例.ViewModel 中的命令将获取点击"项作为其参数.

This is a working example of a method to trigger a command (In the ViewModel) based on the clicked item in a list. The command in the ViewModel will get the "clicked" item as its parameter.

我正在使用 Textblock.InputBindings,它可能是由 Blachshma 链接的 Blend SDK 的一部分,但您不需要任何其他 DLL 来使其工作.

I'm using the Textblock.InputBindings and that might be part of the Blend SDK linked by Blachshma, but you will not need any other DLLs for this to work.

在我的示例中,ViewModel 绑定到 UserControl 的 DataContext,这就是为什么我需要使用 RelativeSource FindAncestor 从我的 TextBlock 中找到 ViewModel.

In my example the ViewModel is bound to the DataContext of the UserControl, that is why I need to use the RelativeSource FindAncestor to find the ViewModel from my TextBlock.

编辑:通过将TextBlockWidth绑定到ListBoxActualWidth来修复宽度问题.

Edit: Fixed the width problem by binding the Width of the TextBlock to the ActualWidth of the ListBox.

只是一个问题,即使列表本身更宽,双击也只有在文本块中的文本内部单击时才有效.

Just one problem, the double click will only work when you click inside the text in the textblock even if the list itself is much wider.

    <ListView ItemsSource="{Binding Model.TablesView}"   Grid.Row="1" 
              SelectedItem="{Binding Model.SelectedTable, Mode=TwoWay}"  >
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=.}" 
                   Width="{Binding Path=ActualWidth, 
                             RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}" >
                    <TextBlock.InputBindings>
                        <MouseBinding MouseAction="LeftDoubleClick" Command="{Binding DataContext.MoveItemRightCommand,
                                        RelativeSource={RelativeSource FindAncestor, 
                                        AncestorType={x:Type UserControl}}}"
                                      CommandParameter="{Binding .}"/>
                    </TextBlock.InputBindings>
                </TextBlock>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

这篇关于如何在mvvm中绑定鼠标双击命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆