我需要在用戶點擊它時摺疊WPF DataGrid的細節行,並在他們再次點擊時重新顯示它。我也想使用單選來保留VisibleWhenSelected的DataGridRoDetailsVisibilityMode。WPF datagrid在點擊時摺疊細節行
我想出了這個解決方案,基於關閉這個帖子在別處:http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/0a45b3a7-46d0-45a9-84b2-0062f07f6fec#eadc8f65-fcc6-41df-9ab9-8d93993e114c
private bool _rowSelectionChanged;
private void dgCompletedJobs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
_rowSelectionChanged = true;
}
private void dgCompletedJobsMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
DependencyObject dep = (DependencyObject)e.OriginalSource;
//navigate up the tree
while (dep != null &&
!(dep is DataGridCell) &&
!(dep is DataGridColumnHeader))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
{
return;
}
DataGridCell dgc = dep as DataGridCell;
if (dgc != null)
{
//navigate further up the tree
while (dep != null && !(dep is DataGridRow))
{
dep = VisualTreeHelper.GetParent(dep);
}
DataGridRow dgr = dep as DataGridRow;
DataGrid dg = sender as DataGrid;
if (dg != null && dgr != null)
{
if (dgr.IsSelected && !_rowSelectionChanged)
{
dg.RowDetailsVisibilityMode =
(dg.RowDetailsVisibilityMode == DataGridRowDetailsVisibilityMode.VisibleWhenSelected)
? DataGridRowDetailsVisibilityMode.Collapsed
: DataGridRowDetailsVisibilityMode.VisibleWhenSelected;
}
else
{
dg.RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.VisibleWhenSelected;
}
}
}
_rowSelectionChanged = false;
}
這似乎很好地解決我的問題,但我有一個令人難忘的懷疑,這可能是更簡單和優雅的完成,特別是因爲我在這個項目上使用MVVM。但是,我認爲這是事件驅動代碼隱藏的可接受使用方式,因爲它純粹是表示邏輯。
有沒有人有更清潔的解決方案?
工作完美。謝謝。 – GeoffCoope