将事件绑定到ViewModel

时间:2011-10-28 13:00:26

标签: c# wpf events xaml mvvm

我正在为我的应用程序使用WPF和PRISM框架。我正在使用的模式是MVVM(Model - View - ViewModel),我试图将ViewLeft中的MouseLeftButtonUp事件从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:当我这样做时,它是否也与(对象发送者)参数一起使用?因为我需要在我的ViewModel中使用DataGrid来获取我刚刚点击的ActiveCell。

修改

事件绑定与Command一起使用!

我在DataGrid中有这个:

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

如何将Tag属性绑定到ViewModel?我知道它已经从ViewModel绑定了,但是你可以看到值来自一个数组/列表,每列的值是不同的。

1 个答案:

答案 0 :(得分:10)

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

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

查看型号:

public ICommand SomeActionCommand { get; set; }

<强> XAML:

<i:InvokeCommandAction Command="{Binding SomeActionCommand}" />
相关问题