How to rewrite this DataGrid MouseLeftButtonUp binding to MVVM?

本小妞迷上赌 提交于 2019-12-24 13:51:26

问题


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 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.

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


回答1:


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>

and in the ViewModel define the MouseLeftButtonUpCommand :

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


来源:https://stackoverflow.com/questions/27586538/how-to-rewrite-this-datagrid-mouseleftbuttonup-binding-to-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!