在WPF中,我使用datagrid行标题中的切换按钮来显示每个父数据网格行作为子数据网格的详细可见性。当我单击切换按钮时,相应父数据网格行的visualstate将更改为“Checked”状态。它运作正常。但同时我想将所有其他父数据网格行视觉状态的视觉状态设置为“未选中”或“正常”而不单击每个切换按钮。我使用以下代码。但它不能正常工作。但是如果我点击每个切换按钮,那么它的视觉状态就会正常变化。
private void ToggleButton_Click(object sender, RoutedEventArgs e)
{
DependencyObject obj = (DependencyObject)e.OriginalSource;
while (!(obj is DataGridRow) && (obj != null))
{
obj = VisualTreeHelper.GetParent(obj);
}
if (obj is DataGridRow)
{
if ((obj as DataGridRow).DetailsVisibility == Visibility.Visible)
{
(obj as DataGridRow).IsSelected = false;
(obj as DataGridRow).DetailsVisibility = System.Windows.Visibility.Collapsed;
}
else if ((obj as DataGridRow).DetailsVisibility == Visibility.Collapsed)
{
for (int i = 0; i < Data_Grid.Items.Count; i++)
{
DataGridRow itm = GetDataGridRowitem(i);
itm.IsSelected = false;
itm.DetailsVisibility = System.Windows.Visibility.Collapsed;
VisualStateManager.GoToElementState(itm, "Unchecked", true);
}
DataTemplate dt = FindResource("tocchild") as DataTemplate;
Data_Grid.RowDetailsTemplate = dt;
(obj as DataGridRow).IsSelected = true;
(obj as DataGridRow).DetailsVisibility = Visibility.Visible;
VisualStateManager.GoToElementState((obj as DataGridRow), "Checked", true);
}
}}
我也试过了,
VisualStateManager.GoToState((obj as DataGridRow), "Checked", true);
请帮帮我。 感谢。
答案 0 :(得分:2)
将datagrid
的第一列设置为此
<DataGridTemplateColumn CellTemplate="{StaticResource ExpandDetails}" Width="30" />
并将此dataTemplate
放入资源
<DataTemplate x:Key="ExpandDetails">
<ToggleButton Name="ShowDetails" Height="20"
IsChecked="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow},
Path=DetailsVisibility,
Converter={StaticResource VisbilityToBooleanConverter},
Mode=TwoWay}"
Margin="4" HorizontalAlignment="Right" FlowDirection="LeftToRight" BorderThickness="0" />
</DataGridTemplateColumn>
然后像这样创建VisbilityToBooleanConverter
public class VisbilityToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (Visibility)value == Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (bool)value ? Visibility.Visible : Visibility.Collapsed;
}
}
答案 1 :(得分:1)
答案 2 :(得分:0)
我通过将值Toggle Button IsChecked设置为True和false来解决它。
FrameworkElement tb = GetTemplateChildByName(row, "RowHeaderToggleButton");
(tb as ToggleButton).IsChecked = false;
GetTemplateChildByName的位置,
public static FrameworkElement GetTemplateChildByName(DependencyObject parent, string name)
{
int childnum = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childnum; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is FrameworkElement &&
((FrameworkElement)child).Name == name)
{
return child as FrameworkElement;
}
else
{
var s = GetTemplateChildByName(child, name);
if (s != null)
return s;
}
}
return null;
}
感谢所有人。