繁体   English   中英

如何重写DataGrid MouseLeftButtonUp绑定到MVVM?

[英]How to rewrite this DataGrid MouseLeftButtonUp binding to MVVM?

我有一个可工作的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));
    }

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

我尝试了DependencyProperty并尝试了RelativeSource绑定,但是无法获取PersonDataGrid_CellClicked来导航到PersonProfile UserControl。

通过使用Blend System.Windows.Interactivity程序集,只要在VM的已定义命令中未使用与视图直接相关的逻辑,就不会违反任何MVVM原理,在此处如何将它与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 
                }));
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM