[英]How to Bind CurrentCell in WPF datagrid using MVVM pattern
I'm learning WPF MVVM pattern. 我正在学习WPF MVVM模式。 I'm stuck in
Binding CurrentCell
of datagrid
. 我陷入了
datagrid
Binding CurrentCell
。 Basically I need the row index and column index of current cell. 基本上我需要当前单元格的行索引和列索引。
<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">
Here is my ViewModel 这是我的ViewModel
private User procedureName = new User();
public DataGridCell CellInfo
{
get { return procedureName.CellInfo; }
//set
//{
// procedureName.CellInfo = value;
// OnPropertyChanged("CellInfo");
//}
}
Here is my Model 这是我的模特
private DataGridCell cellInfo;
public DataGridCell CellInfo
{
get { return cellInfo; }
//set
//{
// cellInfo = value;
// OnPropertyChanged("CellInfo");
//}
}
And in my ViewModel CellInfo
is always null
. 在我的ViewModel中,
CellInfo
始终为null
。 I am not able to get the value from the currentcell
in datagrid
. 我无法从
datagrid
的currentcell
获取值。 Please let me know a way to get CurrentCell
in the ViewModel. 请让我知道一种在ViewModel中获取
CurrentCell
的方法。
if (CellInfo != null)
{
MessageBox.Show("Value is" + CellInfo.Column.DisplayIndex.ToString());
}
After having a quick poke-around I've noticed a very simple solution to your problem. 快速解决后,我注意到了一个非常简单的问题解决方案。
First of all there's two problems rather then one here. 首先,有两个问题而不是一个问题。 You cannot bind a
CellInfo
of a type DataGridCell
, it needs to be DataGridCellInfo
as xaml cannot convert it on its own. 你不能绑定
DataGridCell
类型的CellInfo
,它需要是DataGridCellInfo
因为xaml CellInfo
转换它。
Secondly in your xaml you will need to add Mode=OneWayToSource
or Mode=TwoWay
to your CellInfo
binding. 其次在你的xaml中你需要将
Mode=OneWayToSource
或Mode=TwoWay
到你的CellInfo
绑定中。
Here is a rough example semi-related to your original code 这是一个与原始代码半关联的粗略示例
XAML XAML
<DataGrid AutoGenerateColumns="True"
SelectionUnit="Cell"
SelectionMode="Single"
Height="250" Width="525"
ItemsSource="{Binding Results}"
CurrentCell="{Binding CellInfo, Mode=OneWayToSource}"/>
VM 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!"));
}
}
Just a small tip - if you debug your app and look at the Output window it actually tells you if there is any troubles with your bindings. 只是一个小小的提示 - 如果您调试应用程序并查看“输出”窗口,它实际上会告诉您绑定是否有任何问题。
Hope this helps! 希望这可以帮助!
K. K.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.