首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用MVVM模式在WPF datagrid中绑定CurrentCell

如何使用MVVM模式在WPF datagrid中绑定CurrentCell
EN

Stack Overflow用户
提问于 2013-11-20 03:15:55
回答 1查看 12.7K关注 0票数 5

我正在学习WPF MVVM模式。我被困在datagridBinding CurrentCell里了。基本上,我需要当前单元格的行索引和列索引。

代码语言:javascript
复制
<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

代码语言:javascript
复制
private User procedureName = new User();

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

这是我的模型

代码语言:javascript
复制
private DataGridCell cellInfo;

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

在我的ViewModel中,CellInfo总是null。我无法从datagrid中的currentcell获取值。请告诉我让CurrentCell进入ViewModel的方法。

代码语言:javascript
复制
if (CellInfo != null)
{
    MessageBox.Show("Value is" + CellInfo.Column.DisplayIndex.ToString());
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-20 18:46:49

在快速浏览了一下之后,我发现了一个非常简单的问题解决方案。

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

其次,在xaml中,需要将Mode=OneWayToSourceMode=TwoWay添加到CellInfo绑定中。

下面是一个与原始代码半相关的粗略示例

XAML

代码语言:javascript
复制
<DataGrid AutoGenerateColumns="True"
          SelectionUnit="Cell"
          SelectionMode="Single"
          Height="250" Width="525" 
          ItemsSource="{Binding Results}"
          CurrentCell="{Binding CellInfo, Mode=OneWayToSource}"/>

虚拟机

代码语言:javascript
复制
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.

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20080130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档