如何重写DataGrid MouseLeftButtonUp绑定到MVVM? [英] How to rewrite this DataGrid MouseLeftButtonUp binding to MVVM?

查看:59
本文介绍了如何重写DataGrid MouseLeftButtonUp绑定到MVVM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可工作的MouseLeftButtonUp绑定,我可以从View.cs使用它,但是不能从Viewmodel.cs中使用

I have a working MouseLeftButtonUp binding that I works from the View.cs but that I cannot get working from the Viewmodel.cs

XAML:

 <DataGrid x:Name="PersonDataGrid" AutoGenerateColumns="False" 
     SelectionMode="Single" SelectionUnit ="FullRow"  ItemsSource="{Binding Person}"
     SelectedItem="{Binding SelectedPerson}" 
     MouseLeftButtonUp="{Binding PersonDataGrid_CellClicked}" >

View.cs:

    private void PersonDataGrid_CellClicked(object sender, MouseButtonEventArgs e)
    {
        if (SelectedPerson == null)
            return;

        this.NavigationService.Navigate(new PersonProfile(SelectedPerson));
    }

PersonDataGrid_CellClicked方法无法在ViewModel.cs中使用.我已经尝试阅读有关Blend System.Windows.Interactivity的内容,但是并没有尝试,因为我想在学习MVVM时避免使用它.

PersonDataGrid_CellClicked method will not work from the ViewModel.cs. I've tried reading about Blend System.Windows.Interactivity but have not tried it as I wanted to avoid it while I'm still learning MVVM.

我尝试了DependencyProperty并尝试了RelativeSource绑定,但是无法使PersonDataGrid_CellClicked导航到PersonProfile UserControl.

I've tried DependencyProperty and tried RelativeSource binding but could not get PersonDataGrid_CellClicked to navigate to the PersonProfile UserControl.

推荐答案

,通过使用Blend System.Windows.Interactivity程序集,只要不使用与视图直接相关的逻辑,就不会违反任何MVVM原理.在VM中定义的命令,此处介绍如何将其与MouseLeftButtonUp事件一起使用:

by using the Blend System.Windows.Interactivity assembly you are not violating any of the MVVM principles as long as no logic related directly to the view is used inside the defined command in the VM, here how to used it with the MouseLeftButtonUp Event:

<DataGrid>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseLeftButtonUp" >
                <i:InvokeCommandAction
                      Command="{Binding MouseLeftButtonUpCommand}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </DataGrid>

并在ViewModel中定义MouseLeftButtonUpCommand:

and in the ViewModel define the MouseLeftButtonUpCommand :

private RelayCommand _mouseLeftButtonUpCommand;
    public RelayCommand MouseLeftButtonUpCommand
    {
        get
        {
            return _mouseLeftButtonUpCommand 
                ?? (_mouseLeftButtonUpCommand = new RelayCommand(
                () =>
                {
                    // the handler goes here 
                }));
        }
    }

这篇关于如何重写DataGrid MouseLeftButtonUp绑定到MVVM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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