如何重写此DataGrid MouseLeftButtonUp绑定到MVVM?

时间:2014-12-21 03:43:18

标签: c# wpf mvvm datagrid mouseclick-event

我有一个工作的MouseLeftButtonUp绑定,我从View.cs工作,但我无法从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时想要避免它。

我已尝试过DependencyProperty并尝试使用RelativeSource绑定但无法获取PersonDataGrid_CellClicked以导航到PersonProfile UserControl。

1 个答案:

答案 0 :(得分:2)

通过使用Blend System.Windows.Interactivity程序集,您不会违反任何MVVM原则,只要在VM中定义的命令中没有直接与视图相关的逻辑,这里如何将它与MouseLeftButtonUp一起使用事件:

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

并在ViewModel中定义MouseLeftButtonUpCommand:

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