首页 > 解决方案 > Wpf data grid CurrentCell property fires only once MVVM

问题描述

I have a datagrid that looks like:

<DataGrid x:Name="Applications" CanUserResizeColumns="False" CanUserResizeRows="False"  
 AutoGenerateColumns="false" CanUserAddRows="false" ItemsSource="{Binding Applications}" 
 SelectionMode="Single"
 CurrentCell="{Binding CellInfo, Mode=TwoWay}">

And I have a question about CurrentCell, it is binded to poeprty in view model that looks like:

    private DataGridCellInfo cellInfo;
    public DataGridCellInfo CellInfo
    {
        get => cellInfo;
        set
        {
            cellInfo = value;
            OnPropertyChanged();

            if (cellInfo.Column.DisplayIndex == 1)
            {
                var selectedApplication = (ExtendedApplicationFile)cellInfo.Item;
                ExpandAppDetailsCommand.Execute(selectedApplication);
            }
        }
    }

And what it does, it sets correct item and sends it to command that will expend and hide row details window.

Problem is if I click once property is set and it will expand, but when I click second time on same cell, property is not setting and details row is not collapsing. It will work again when I click other cell and get back to it, but that is not I am aiming for.

标签: c#wpf

解决方案


根据评论中的信息,我想出了简单的解决方案,我添加了带有事件触发器的单元格模板:

<DataGridTemplateColumn.CellTemplate>
       <DataTemplate>
             <Label Content="{Binding Name}" Width="350">
                   <i:Interaction.Triggers>
                         <i:EventTrigger EventName="MouseDown">
                                  <i:InvokeCommandAction Command="{Binding DataContext.ExpandAppDetailsCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}" CommandParameter="{Binding}"/>
                          </i:EventTrigger>
                    </i:Interaction.Triggers>
                 </Label>
           </DataTemplate>                
</DataGridTemplateColumn.CellTemplate>

每次单击单元格事件触发并切换详细信息视图时都使用薄。


推荐阅读