我有一個DataGrid與分組的ItemsSource。每個組都有一個擴展器,因此我可以展開/摺疊所有組。現在,我試圖在默認情況下摺疊所有組,但是保留第一組。項目源是動態的,所以我不能建立任何轉換器來檢查組名。我必須通過小組索引來完成。DataGrid - 摺疊除第一個以外的所有組
在XAML中可以做到嗎?或在代碼隱藏?
請幫忙。
我有一個DataGrid與分組的ItemsSource。每個組都有一個擴展器,因此我可以展開/摺疊所有組。現在,我試圖在默認情況下摺疊所有組,但是保留第一組。項目源是動態的,所以我不能建立任何轉換器來檢查組名。我必須通過小組索引來完成。DataGrid - 摺疊除第一個以外的所有組
在XAML中可以做到嗎?或在代碼隱藏?
請幫忙。
我不相信它可以在XAML中完成,但它可以在代碼隱藏中完成。這是我在Silverlight中測試的一個解決方案。它應該可以在WPF中工作。
// If you don't have a direct reference to the grid's ItemsSource,
// then cast the grid's ItemSource to the type of the source.
// In this example, I used a PagedCollectionView for the source.
PagedCollectionView pcv = (PagedCollectionView)myDataGrid.ItemsSource;
// Using the PagedCollectionView, I can get a reference to the first group.
CollectionViewGroup firstGroup = (CollectionViewGroup)pcv.Groups[0];
// First collapse all groups (if they aren't already collapsed).
foreach (CollectionViewGroup group in pcv.Groups)
{
myDataGrid.ScrollIntoView(group, null); // This line is a workaround for a problem with collapsing groups when they aren't visible.
myDataGrid.CollapseRowGroup(group, true);
}
// Now expand only the first group.
// If using multiple levels of grouping, setting 2nd parameter to "true" will expand all subgroups under the first group.
myDataGrid.ExpandRowGroup(firstGroup, false);
// Scroll to the top, ready for the user to see!
myDataGrid.ScrollIntoView(firstGroup, null);
這可能是有點晚了,但爲了幫助類似的問題,確定了「視覺樹的輔助類」會在這種情況下有幫助。
// the visual tree helper class
public static class VisualTreeHelper
{
public static Collection<T> GetVisualChildren<T>(DependencyObject current) where T : DependencyObject
{
if (current == null)
return null;
var children = new Collection<T>();
GetVisualChildren(current, children);
return children;
}
private static void GetVisualChildren<T>(DependencyObject current, Collection<T> children) where T : DependencyObject
{
if (current != null)
{
if (current.GetType() == typeof(T))
children.Add((T)current);
for (int i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(current); i++)
{
GetVisualChildren(System.Windows.Media.VisualTreeHelper.GetChild(current, i), children);
}
}
}
}
// then you can use the above class like this:
Collection<Expander> collection = VisualTreeHelper.GetVisualChildren<Expander>(dataGrid1);
foreach (Expander expander in collection)
expander.IsExpanded = false;
collection[0].IsExpanded = true;
要歸功於this forum
我能在我的視圖模型來解決這個問題。
Expander在DataGrids GroupStyle的模板中定義。綁定必須是雙向的,但是明確觸發,因此在視圖中單擊不會更新ViewModel。謝謝Rachel。
<Expander IsExpanded="{Binding DataContext.AreAllGroupsExpanded, RelativeSource={RelativeSource AncestorType={x:Type local:MyControl}}, UpdateSourceTrigger=Explicit}">
...
</Expander>
然後我可以在我的ViewModel中設置屬性AreAllGroupsExpanded
。
非常好的解決問題的辦法! – MartinZPetrov