我已经为此苦苦挣扎了一段时间了。我的应用程序中有一个“主/详细信息”布局,并且像许多其他人一样面临着 DataGrid 在禁用它时丢失其选择的问题。本质上,从列表中选择一个元素来填充一系列字段后,用户按下“编辑”,这会禁用 DataGrid 并启用所有表单的字段。按“保存”按钮将在保存数据后恢复这些操作......非常简单。
我在 Windows 7 上使用 VS 2010 在 .Net Framework 4 中进行开发。
我尝试过的:
1)基于这个帖子 http://social.msdn.microsoft.com/Forums/hu-HU/wpf/thread/97920757-a0ed-4488-b1a7-2a2b55fb1014,我曾尝试使用WPF Toolkit 2009年6月版中的DataGrid,但我也有同样的反应。
2)基于此 WPF CodePlex 错误报告 http://wpf.codeplex.com/workitem/13022,我尝试创建一个基于 DataGrid 的自定义控件并重写 OnIsEnabledChanged 调用以删除对“UnselectAllCells”的调用,但由于没有代码示例,我什至无法让它触发一次。我努力了:
public class FormMainDataGrid : DataGrid
{
static FormMainDataGrid()
{
IsEnabledProperty.OverrideMetadata(typeof(FormMainDataGrid), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnIsEnabledChanged)));
}
public FormMainDataGrid() : base() { }
private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
d.CoerceValue(CanUserAddRowsProperty);
d.CoerceValue(CanUserDeleteRowsProperty);
//this was added in new version !!!
/*
if (!(bool)(e.NewValue))
{
((DataGrid)d).UnselectAllCells();
}
*/
// Many commands use IsEnabled to determine if they are enabled or not
CommandManager.InvalidateRequerySuggested();
}
}
但一旦我禁用 DataGrid,这仍然会取消选择当前选定的行。我尝试像这样解释最后的评论(在 Codeplex 错误报告中):
public class FormMainDataGrid : DataGrid
{
static FormMainDataGrid()
{
}
public static void OverrideStuff()
{
IsEnabledProperty.OverrideMetadata(typeof(FormMainDataGrid), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnIsEnabledChanged)));
}
public FormMainDataGrid() : base() { }
private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
d.CoerceValue(CanUserAddRowsProperty);
d.CoerceValue(CanUserDeleteRowsProperty);
//this was added in new version !!!
/*
if (!(bool)(e.NewValue))
{
((DataGrid)d).UnselectAllCells();
}
*/
// Many commands use IsEnabled to determine if they are enabled or not
CommandManager.InvalidateRequerySuggested();
}
}
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
FormMainDataGrid.OverrideStuff();
base.OnStartup(e);
}
}
但这甚至不会触发该方法的修改版本。
首先,我的做法正确吗?考虑到取消选择是由该方法引起的,我可以完全替换我自己的方法对“OnIsEnabledChanged”的内部调用吗?
我还有其他方法可以解决这个问题吗?
或者更具体地说,我如何停止对此方法的基本版本的调用,因为它不是覆盖,因此我不能“不”调用base.OnIsEnabledChanged
?
多谢!