gpt4 book ai didi

c# - 如何将此 DataGrid MouseLeftButtonUp 绑定(bind)重写为 MVVM?

转载 作者:行者123 更新时间:2023-12-03 10:28:07 29 4
gpt4 key购买 nike

我有一个工作 MouseLeftButtonUp 绑定(bind),我从 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}" >

查看.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 绑定(bind),但无法让 PersonDataGrid_CellClicked 导航到 PersonProfile UserControl。

最佳答案

通过使用 Blend System.Windows.Interactivity 程序集,只要在 VM 中定义的命令中没有使用与 View 直接相关的逻辑,您就不会违反任何 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
}));
}
}

关于c# - 如何将此 DataGrid MouseLeftButtonUp 绑定(bind)重写为 MVVM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27586538/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com