繁体   English   中英

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

[英]How to Bind CurrentCell in WPF datagrid using MVVM pattern

我正在学习WPF MVVM模式。 我陷入了datagrid Binding CurrentCell 基本上我需要当前单元格的行索引和列索引。

<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">

这是我的ViewModel

private User procedureName = new User();

public  DataGridCell   CellInfo
{
    get { return procedureName.CellInfo; }
    //set
    //{
    //    procedureName.CellInfo = value;
    //    OnPropertyChanged("CellInfo");
    //}
}

这是我的模特

private DataGridCell cellInfo;

public DataGridCell CellInfo
{
    get { return cellInfo; }
    //set
    //{
    //    cellInfo = value;
    //    OnPropertyChanged("CellInfo");
    //}
}

在我的ViewModel中, CellInfo始终为null 我无法从datagridcurrentcell获取值。 请让我知道一种在ViewModel中获取CurrentCell的方法。

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

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

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

其次在你的xaml中你需要将Mode=OneWayToSourceMode=TwoWay到你的CellInfo绑定中。

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

XAML

<DataGrid AutoGenerateColumns="True"
          SelectionUnit="Cell"
          SelectionMode="Single"
          Height="250" Width="525" 
          ItemsSource="{Binding Results}"
          CurrentCell="{Binding CellInfo, Mode=OneWayToSource}"/>

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!"));
    }
}

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

希望这可以帮助!

K.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM