Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

c# - How to bind mousedouble click command in mvvm

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}"> 

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...