将事件绑定到ViewModel

7

我正在使用WPF和PRISM框架开发我的应用程序。我使用的模式是MVVM(Model-View-ViewModel),并且我正在尝试将代码后台中的MouseLeftButtonUp事件从View传递到ViewModel中(以便事件符合MVVM规则)。目前我有以下代码:

View.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:如果我这样做,(object sender)参数也可以工作吗?因为我需要在ViewModel中得到我刚刚点击的ActiveCell所在的DataGrid。
编辑:
使用Command来绑定事件成功了!
我在DataGrid中添加了以下内容:
<DataGridTextColumn Header="Okt" Width="*" x:Name="test" >
     <DataGridTextColumn.ElementStyle>
           <Style TargetType="{x:Type TextBlock}">
             <Setter Property="Tag" Value="{Binding Months[9].AgreementID}"/>

如何将标签属性绑定到ViewModel?我知道它已经从ViewModel绑定,但是您可以看到该值来自数组/列表,并且每列的值不同。

1个回答

10

InvokeCommandAction要求将ICommand绑定到数据而不是事件处理程序(如你绑定的)。

因此,你可以在ViewModel中引入一个命令并将其绑定到它:

View Model:

public ICommand SomeActionCommand { get; set; }

XAML:

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

谢谢,那个完美地解决了!你有没有建议可以将DataGrid与命令一起传递(作为参数或其他方式),这样我就可以在我的ViewModel中访问它? - Jelle Capenberghs
@Jelle Capenberghs:不,将整个UI容器传递到ViewModel中不是MVVM方法,ViewModel不应该知道任何特定的UI实现(今天你使用rid,但也许明天会用TreeView,因此ViewModel必须进行重构,这是错误的)。您在此命令中尝试做什么? - sll
我需要在我的ViewModel中获取我点击的单元格,因为该单元格包含一个TextBlock,其中包含我在ViewModel中需要的信息。- 已标记为答案,因为ICommand是我最需要的! - Jelle Capenberghs
我建议绑定文本本身 <TextBox Text="{Binding ViewModelProperty}" >,而不是使用事件的复杂情况。 - sll
请问一下,"i"是什么命名空间? - Fandi Susanto
请在谷歌上搜索“Interaction.Behavuiours”。 - sll

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接