Wpf从代码背后改变可见性

时间:2015-03-15 16:18:37

标签: c# wpf

我正在尝试从后面的代码中更改数据网格的可见性,但它无法正常工作

 private void afch_data_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        if (donne_compte.IsVisible) // this is a grid and It's visible
        {
           dgComptes.Visibility = Visibility.Visible; 
           //when I breakpoint here , I find that the datagrid visibilty   `property is still set to hidden  

        }
    }

EDIT 这是我的datagrid Xaml这是一个简单的:

<DataGrid x:Name="dgComptes" CanUserAddRows="False"   IsSynchronizedWithCurrentItem="True"  ItemsSource="{Binding ComCollection}"  RowHeaderWidth="0"  HorizontalScrollBarVisibility="Disabled"  HorizontalAlignment="Left" Margin="529.534,84.016,-390.033,0" VerticalAlignment="Top" Height="Auto"  MaxHeight="200"  Width="395.429" RenderTransformOrigin="0.5,0.5" Background="#FFCFCFCF"  ColumnWidth="*" HorizontalGridLinesBrush="Black" VerticalGridLinesBrush="Black" RowBackground="#FFCFCFCF" AreRowDetailsFrozen="True" Style="{DynamicResource DataGridStyle2}" CellEditEnding="dataGrid1_CellEditEnding" CurrentCellChanged="dataGrid1_CurrentCellChanged" SelectionChanged="dataGrid1_SelectionChanged" AutoGeneratingColumn="dataGrid1_AutoGeneratingColumn" AutoGenerateColumns="False" >

                <DataGrid.Columns >

                    <DataGridTemplateColumn x:Name="champ_supp2" >
                        <DataGridTemplateColumn.CellTemplate >
                            <DataTemplate>
                                <Button x:Name="supprime" Content="Button" Width="30" Height="30" Style="{DynamicResource ButtonStyle12}" Click="supprime_Click"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>


                    <DataGridTextColumn   Header="Id"  Binding="{Binding ID}" />
                    <DataGridTextColumn   Header="Taille"  Binding="{Binding TAILLE}"  />
                    <DataGridTextColumn   Header="Client" Binding="{Binding CLIENT}"   />
                    <DataGridTextColumn   Header="D.arrivée" Binding="{Binding D_ARRIVEE}"   />
                    <DataGridTextColumn   Header="D.départ" Binding="{Binding D_DEPART}"   />

                </DataGrid.Columns>



            </DataGrid>

1 个答案:

答案 0 :(得分:4)

<强>声明

<小时/> 设置可见性适用于DataGrid。刚检查过,这应该完美无缺:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="25"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Button Grid.Row="0" Content="Show DataGrid" Click="Button_Click"/>
    <DataGrid Visibility="Hidden"
        Grid.Row="1"
        x:Name="gridToHide">
    </DataGrid>

</Grid>

代码背后:

private void Button_Click(object sender, RoutedEventArgs e)
{
    this.gridToHide.Visibility = Visibility.Visible;
}


<强>解决方案

<小时/> 可能不允许/阻止设置Visibility的{​​{1}}属性的内容是父元素的UIElement。 如果父元素隐藏,则无法使其祖先可见。 Visibility的值将被更改,但Visibility将保持 IsVisible
要解决此问题,您必须检查元素(父项)的逻辑树并搜索隐藏的元素。