【发布时间】:2014-10-20 22:36:53
【问题描述】:
我将 MVVM 模式用于一个简单的 WPF 应用程序。我的视图有一个 DataGrid 和一个按钮。我的 DataGrid 有一个附加属性(附加属性的目的与我的问题并不真正相关)。
如果我单击 DataGrid 中的一个单元格,然后单击按钮,我的附加属性的“OnIsCurrentCellFocusedPropertyChanged”方法就会执行。这是这个方法的一个 sn-p:
public static void OnIsCurrentCellFocusedPropertyChanged(DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
// This works; I confirmed it's returning the actual DataGrid in my view
// and not another "new" instance of DataGrid.
var datagrid = source as DataGrid;
if (!(bool)e.NewValue) return;
// datagrid.CurrentCell is null!
DataGridColumn cellColumn = datagrid.CurrentCell.Column;
int colNumber = cellColumn.DisplayIndex;
// datagrid.SelectedIndex is -1!
int rowNumber = datagrid.SelectedIndex;
// more code....
}
XAML sn-p 在我的 DataGrid 中显示 AttachedProperty:
<DataGrid FrozenColumnCount="1" local:CurrentCellFocusedExtension.IsCurrentCellFocused="{Binding IsFocused}" x:Name="companies" ItemsSource="{Binding Companies}"/>
我的问题是,我想从我的 DataGrid 中获取 CurrentCell,但 CurrentCell == null。 我想这是因为当我单击 Button 时,焦点转移到 Button 并远离我的DataGrid(尽管单元格在视图中仍处于可见状态)。同样麻烦的是 SelectedIndex 返回-1...我什至无法获得行索引,更不用说选定的单元格了。
帮助?
一个想法:我可能可以继承 DataGrid 并添加一个公共的“最后选择的单元格”属性。
【问题讨论】:
-
我猜(如果这工作正常)当 DG 获得焦点或失去焦点时,它会触发?如果这是真的,网格可以在没有聚焦单元格的情况下获得焦点,并且可以在没有聚焦单元格的情况下失去焦点。每当焦点单元发生变化时,它根本不应该发生变化。您可能想要更改附加属性以绑定到 CurrentCell,它应该告诉您当前哪个单元格具有焦点。 msdn.microsoft.com/en-us/library/…
-
附加属性应该有助于在撤消/重做操作更改 DataGrid 的 ItemsSource 后重置具有焦点的单元格。这是一个示例:1)用户单击第 3 行中的单元格。2)用户单击撤消按钮。 3) ViewModel 将公共 bool 属性设置为 false,重置集合(用作 DataGrid 的 ItemsSource),然后将 bool 属性设置为 true。 AttachedProperty 是绑定到 VM 的 bool 的 bool。它应该重新聚焦数据网格的选定单元格(本示例中的第 3 行中的单元格)。
-
没有代码在其 ItemsSource 更改后重置数据网格的选定行,数据网格的选定行将更改为第 1 行。我想取消此行为,因为当她单击撤消按钮时用户会感到困惑并且数据网格更改了焦点行。她必须手动重新选择她所在的行(如果不是第 1 行)以查看撤消的效果。
-
似乎撤消功能应该在虚拟机中实现。我已经这样做了(
BeginEdit和AcceptEdit/RevertEdit方法)并创建了我自己的 WF4 模型项版本,它包装了 POCO 并提供更新通知、附加属性和其他以 UI 为中心的支持,如撤消/重做跟踪。至于这个版本……不确定它是否可行,因为你必须在 DG 上使用有限的表面。也许扩展 DG 以添加撤消/重做? -
实际上,我的虚拟机实现了撤消/重做命令(借助静态“UndoManager”类,该类负责深度克隆传递给它的对象,然后将其添加到其撤消堆栈中(堆栈) 或重做堆栈)。回到您的第一个建议,您认为我应该将 CurrentCell 添加为 VM 属性吗?这可能行得通。