WPF基于另一个元素设置DataGridTextColumn可见性

时间:2016-04-04 15:39:42

标签: wpf datagrid

这应该很简单,但令我感到困惑。我想根据另一个元素的Visibility设置DataGridTextColumn之一的Visibility。所以我这样做了:

<StackPanel>
    <TextBlock Text="This is the text" Name="MyTextBlock" Margin="5">
        <TextBlock.Style>
            <Style TargetType="{x:Type TextBlock}" >
                <Setter Property="Visibility" Value="Visible" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=MyTextBox, Path=Text}" Value="0">
                        <Setter Property="Visibility" Value="Collapsed" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
    <TextBox Text="2"   Name="MyTextBox"  />
    <DataGrid AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="H1" />
            <DataGridTextColumn Header="H2" Visibility="{Binding ElementName=MyTextBlock, Path=Visibility}" />
        </DataGrid.Columns>
    </DataGrid>
</StackPanel>

Visibility MyTextBlock的工作正确,但DataGridTextColumn H2始终可见。我做错了什么?

1 个答案:

答案 0 :(得分:1)

@Ruben解决方案有效。对于任何关心此处的人都是工作代码:

<StackPanel>
    <StackPanel.Resources>
        <FrameworkElement x:Key="ProxyElement"
                     DataContext="{Binding ElementName=MyTextBlock}"/>
    </StackPanel.Resources>
    <TextBlock Text="This is the text" Name="MyTextBlock"  Margin="5">
        <TextBlock.Style>
            <Style TargetType="{x:Type TextBlock}" >
                <Setter Property="Visibility" Value="Visible" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=MyTextBox, Path=Text}" Value="0">
                        <Setter Property="Visibility" Value="Collapsed" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
    </TextBlock>
    <TextBox Text="0"   Name="MyTextBox"  />
    <ContentControl Visibility="Collapsed" Content="{StaticResource ProxyElement}"/>
    <DataGrid AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="H1" />
            <DataGridTextColumn Header="H2" Visibility="{Binding DataContext.Visibility,  Source={StaticResource ProxyElement}}" />
        </DataGrid.Columns>
    </DataGrid>
</StackPanel>