我有一个带有详细信息行的数据网格,例如:
<DataGrid x:Name="Applications" CanUserResizeColumns="False" CanUserResizeRows="False" RowStyle="{StaticResource CollapsedRow}" AutoGenerateColumns="false" CanUserAddRows="false" ItemsSource="{Binding Applications}">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content='˅' FontSize="9" Name="ExpanderButton" Click="OnGroupChange" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Width="181" Header="Application name" Binding="{Binding Name, Mode=OneWay}" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<!-- SOME DETAILS HERE -->
</DataGrid.RowDetailsTemplate>
</DataGrid>
现在的想法是,我有一个带有附加列的数据网格,并带有一个按钮,该按钮将扩展明细行,所以我的代码是:
private void OnGroupChange(object sender, RoutedEventArgs e)
{
CollapseGroupDetails();
for (var visible = (Visual)sender; visible != null; visible = VisualTreeHelper.GetParent(visible) as Visual)
{
if (visible.GetType() != typeof(DataGridRow))
continue;
var row = (DataGridRow)visible;
var appName = (ExtenedApplicationFile)row.Item;
((ApplicationsViewModel)DataContext).SelectedApplicationFile = appName;
row.DetailsVisibility = row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}
Applications.UpdateLayout();
}
private void CollapseGroupDetails()
{
foreach (object item in Applications.ItemsSource)
{
if (!(Applications.ItemContainerGenerator.ContainerFromItem(item) is DataGridRow row) || row.DetailsVisibility != Visibility.Visible)
continue;
row.DetailsVisibility = Visibility.Collapsed;
break;
}
}
所以它的工作原理是:我单击一个按钮,它展开了所选网格行的详细信息行,然后关闭了其他行,但是问题是当我单击一个打开的行上的按钮时,我希望它折叠起来,但是
row.DetailsVisibility = row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
此属性的值已经折叠,并且将属性再次设置为可见,但是当我删除时:
CollapseGroupDetails();
方法有效,但是如果我单击另一行的按钮,则先前选择的详细信息行将保持打开状态。我检查了是否选择了正确的行,但检查了它的索引并且它是正确的。有没有办法结合起来?
答案 0 :(得分:1)
您可以在设置属性之前创建Visibility
值的临时副本:
private void OnGroupChange(object sender, RoutedEventArgs e)
{
DataGridRow row = null;
for (var visible = (Visual)sender; visible != null; visible = VisualTreeHelper.GetParent(visible) as Visual)
{
if (visible.GetType() != typeof(DataGridRow))
continue;
row = (DataGridRow)visible;
var appName = (ExtenedApplicationFile)row.Item;
((ApplicationsViewModel)DataContext).SelectedApplicationFile = appName;
break;
}
if (row != null)
{
Visibility currentVisibility = row.DetailsVisibility;
CollapseGroupDetails();
row.DetailsVisibility = currentVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}
else
{
CollapseGroupDetails();
}
Applications.UpdateLayout();
}