c# - 将事件绑定(bind)到 ViewModel

标签 c# wpf events xaml mvvm

我正在为我的应用程序使用 WPF 和 PRISM 框架。我使用的模式是 MVVM(模型 - View - ViewModel),我试图将 MouseLeftButtonUp 事件从 View 中的代码隐藏带到 ViewModel(因此事件将根据 MVVM 规则)。现在我有这个:

查看.xaml:

<DataGrid x:Name="employeeGrid" Height="250" Margin="25,0,10,0" ItemsSource="{Binding DetacheringenEmployeesModel}" IsReadOnly="True" ColumnHeaderStyle="{DynamicResource CustomColumnHeader}" AutoGenerateColumns="False" RowHeight="30">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseLeftButtonUp">
                 <i:InvokeCommandAction Command="{Binding EmployeeGrid_MouseLeftButtonUp}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
<DataGrid.Columns>

View.xaml.cs(代码隐藏):

public partial class UC1001_DashBoardConsultants_View
{
    public UC1001_DashBoardConsultants_View(UC1001_DashboardConsultantViewModel viewModel)
    {
            InitializeComponent();
            DataContext = viewModel;
    }
}

ViewModel.cs:

 public void EmployeeGrid_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
 {
     // insert logic here
 }

主要思想是,当我单击 DataGrid 中的一个单元格时,将触发该事件。我首先在后面的代码中尝试了它,它起作用了。到目前为止,我已经了解了 EventTriggers,但是当我调试并单击一个单元格时,我的调试器没有进入该方法。

有没有人知道如何解决这个问题?提前致谢!

PS:当我这样做时,它是否也适用于(对象发送者)参数?因为我需要我的 ViewModel 中的 DataGrid 来获取我刚刚单击的 ActiveCell。

编辑:

事件绑定(bind)与命令一起工作!

我的 DataGrid 中有这个:

<DataGridTextColumn Header="Okt" Width="*" x:Name="test" >
     <DataGridTextColumn.ElementStyle>
           <Style TargetType="{x:Type TextBlock}">
             <Setter Property="Tag" Value="{Binding Months[9].AgreementID}"/>

如何将 Tag 属性绑定(bind)到 ViewModel?我知道它已经从 ViewModel 绑定(bind),但正如您所见,该值来自数组/列表,并且每列的值都不同。

最佳答案

InvokeCommandAction需要绑定(bind) ICommand 而不是您绑定(bind)的事件处理程序 (EmployeeGrid_MouseLeftButtonUp)。

所以你可以在 ViewModel 中引入一个命令并绑定(bind)到它:

查看模型:

public ICommand SomeActionCommand { get; set; }

XAML:

<i:InvokeCommandAction Command="{Binding SomeActionCommand}" />

关于c# - 将事件绑定(bind)到 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7929611/

相关文章:

c# - 尝试在 540 万条记录中查找一条记录时,如何提高 varchar(400) 的查询性能

wpf - WPF中 "LabelLink"控件的单击事件的绑定(bind)方法-Caliburn

c# - 从两种颜色(从渐变)计算中间色

events - 事件处理程序和事件监听器之间有什么区别(如果有)?

jquery - 在 jQuery 中触发 keyup 事件

c# - 单个 C++/CLI 方法可包装许多类型特定的 C 函数

c# - 是否有必要取消订阅事件?

c# - 在 WPF 中实现暂停

wpf - 如何使用 ObservableCollection 源实现 XAML 单选按钮控件?

c# - 这行 C# 代码实际上做了什么?