【问题标题】:DataGrid Single Cell row and column from click using MVVM使用 MVVM 单击 DataGrid 单个单元格行和列
【发布时间】:2015-10-03 13:38:10
【问题描述】:

我有 DataGrid,我正在尝试使用 MVVM 获取选定单元格的单元格详细信息(列、行​​和值),并避免对后面的代码进行任何更改。

我的数据网格是这样的

<DataGrid x:Name="MyDataGrid" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=MyData}" AutoGenerateColumns="False" IsReadOnly="True" GridLinesVisibility="None" SelectionUnit="Cell">
    <DataGrid.Columns>
        <DataGridTextColumn  Header="a" Width="130" Binding="{Binding Path=A}"/>
        <DataGridTextColumn  Header="b"   Width="100" Binding="{Binding Path=B}"/>
        <DataGridTextColumn  Header="c"   Width="100" Binding="{Binding Path=C}"/>
    </DataGrid.Columns>
    <DataGrid.InputBindings>
        <MouseBinding Gesture="LeftClick"  Command="{Binding DataGridLeftClick}" CommandParameter="{Binding ElementName=MyDataGrid, Path=SelectedCells}" />
    </DataGrid.InputBindings>

在我的 ViewModel 中

   DataGridLeftClick = new RelayCommand(LeftClick);
   ...

   public ICommand DataGridLeftClick { get; private set; }

   public void LeftClick(object obj)
   {   
       log.Info(obj);
   }

该命令有效,但有两件事 obj 的值始终为空。如果我删除网格的 SelectionUnit(所以我假设它默认为 FullRow),那么我会得到完整行单元格的数据。如何获取被点击的单个单元格的行、索引和值?

谢谢, 尼克

【问题讨论】:

    标签: c# wpf mvvm datagrid model-view


    【解决方案1】:

    您是否考虑过 DataGridView.CurrentCell 属性以及绑定到 VM {Binding CurrentCellVMProperty, Mode=OneWayToSource}。

    另请参阅此答案:How to Bind CurrentCell in WPF datagrid using MVVM pattern

    【讨论】:

    • 正是我想要的。花了很多时间在网上搜索,但没有遇到这个。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 2012-05-13
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多