【问题标题】:Bind event to ViewModel将事件绑定到 ViewModel
【发布时间】:2011-12-17 07:03:44
【问题描述】:

我正在为我的应用程序使用 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 中的 DataGrid 来获取我刚刚点击的 ActiveCell。

编辑:

事件绑定与命令一起使用!

我的 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 绑定,但正如您所见,该值来自一个 Array/List 并且每列的值不同。

【问题讨论】:

    标签: c# wpf events xaml mvvm


    【解决方案1】:

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

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

    查看模型:

    public ICommand SomeActionCommand { get; set; }
    

    XAML:

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

    【讨论】:

    • 谢谢,效果很好!您是否还有建议将 DataGrid 与命令(作为参数或其他内容)一起传递,以便我可以在我的 ViewModel 中访问它?
    • @Jelle Capenberghs :不,在 ViewModel 中传递整个 UI 容器不是 MVVM 方法,ViewModel 不应该知道任何有关特定 UI 实现的信息(今天你正在使用,但也许明天 - TreeView 所以ViewModel 必须重构,这是错误的)。你想在这个命令中做什么?
    • 我需要获取我在 ViewModel 中单击的 Cell,因为 Cell 包含一个 TextBlock,其中包含我在 ViewModel 中需要的信息。 - 已标记为答案,因为 ICommand 主要是我需要的!
    • 我建议绑定文本本身&lt;TextBox Text="{Binding ViewModelProperty}" &gt;,而不是这样复杂的事件场景
    • 有人能告诉我“i”是什么命名空间吗?
    猜你喜欢
    • 1970-01-01
    • 2017-12-14
    • 2011-10-31
    • 2019-02-03
    • 1970-01-01
    • 2013-02-11
    • 2021-12-01
    • 1970-01-01
    • 2017-04-07
    相关资源
    最近更新 更多