我正在学习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。我无法从datagrid中的currentcell获取值。请告诉我让CurrentCell进入ViewModel的方法。
if (CellInfo != null)
{
MessageBox.Show("Value is" + CellInfo.Column.DisplayIndex.ToString());
}发布于 2013-11-20 18:46:49
在快速浏览了一下之后,我发现了一个非常简单的问题解决方案。
首先,这里有两个问题,而不是一个。您不能绑定DataGridCell类型的CellInfo,它需要是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}"/>虚拟机
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.
https://stackoverflow.com/questions/20080130
复制相似问题