【问题标题】:How to rewrite this DataGrid MouseLeftButtonUp binding to MVVM?如何将此 DataGrid MouseLeftButtonUp 绑定重写为 MVVM?
【发布时间】:2014-12-21 03:43:17
【问题描述】:

我有一个可用的 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。

【问题讨论】:

    标签: c# wpf mvvm datagrid mouseclick-event


    【解决方案1】:

    通过使用 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 
                    }));
            }
        }
    

    【讨论】:

    • 谢谢。鼠标按钮现在触发处理程序逻辑。我现在有另一个问题,因为我切换到 UserControl 而不是 Page,我没有意识到这会破坏 NavigationService 的使用。
    猜你喜欢
    • 1970-01-01
    • 2015-08-06
    • 2018-02-07
    • 1970-01-01
    • 2011-05-25
    • 2021-07-07
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多