如何使用MVVM模式在WPF数据网格中绑定CurrentCell

Bha*_*h T 5 c# wpf xaml datagrid mvvm

我正在学习WPF MVVM模式.我被困在Binding CurrentCelldatagrid.基本上我需要当前单元格的行索引和列索引.

<DataGrid AutoGenerateColumns="True" 
          SelectionUnit="Cell" 
          CanUserDeleteRows="True" 
          ItemsSource="{Binding Results}" 
          CurrentCell="{Binding CellInfo}" 
          Height="282" 
          HorizontalAlignment="Left" 
          Margin="12,88,0,0" 
          Name="dataGrid1" 
          VerticalAlignment="Top" 
          Width="558" 
          SelectionMode="Single">
Run Code Online (Sandbox Code Playgroud)

这是我的ViewModel

private User procedureName = new User();

public  DataGridCell   CellInfo
{
    get { return procedureName.CellInfo; }
    //set
    //{
    //    procedureName.CellInfo = value;
    //    OnPropertyChanged("CellInfo");
    //}
}
Run Code Online (Sandbox Code Playgroud)

这是我的模特

private DataGridCell cellInfo;

public DataGridCell CellInfo
{
    get { return cellInfo; }
    //set
    //{
    //    cellInfo = value;
    //    OnPropertyChanged("CellInfo");
    //}
}
Run Code Online (Sandbox Code Playgroud)

而在我的ViewModel CellInfo中总是如此null.我没能获得从价值currentcelldatagrid.请让我知道一种CurrentCell进入ViewModel的方法.

if (CellInfo != null)
{
    MessageBox.Show("Value is" + CellInfo.Column.DisplayIndex.ToString());
}
Run Code Online (Sandbox Code Playgroud)

kos*_*dos 14

快速解决后,我注意到了一个非常简单的问题解决方案.

首先,有两个问题而不是一个问题.你不能绑定一个CellInfo类型 DataGridCell,它需要是DataGridCellInfo因为xaml不能自己转换它.

其次在你的xaml中你需要添加Mode=OneWayToSource或绑定Mode=TwoWay你的CellInfo绑定.

这是一个与原始代码半关联的粗略示例

XAML

<DataGrid AutoGenerateColumns="True"
          SelectionUnit="Cell"
          SelectionMode="Single"
          Height="250" Width="525" 
          ItemsSource="{Binding Results}"
          CurrentCell="{Binding CellInfo, Mode=OneWayToSource}"/>
Run Code Online (Sandbox Code Playgroud)

VM

private DataGridCellInfo _cellInfo;
public DataGridCellInfo CellInfo
{
    get { return _cellInfo; }
    set
    {
        _cellInfo = value;
        OnPropertyChanged("CellInfo");
        MessageBox.Show(string.Format("Column: {0}",
                        _cellInfo.Column.DisplayIndex != null ? _cellInfo.Column.DisplayIndex.ToString() : "Index out of range!"));
    }
}
Run Code Online (Sandbox Code Playgroud)

只是一个小小的提示 - 如果您调试应用程序并查看"输出"窗口,它实际上会告诉您绑定是否有任何问题.

希望这可以帮助!

K.