Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataTrigger to display and hide grid column XAML

I have an WPF application that contains a grid. The grid is split into 3 columns with the 3rd grid having zero width upon loading.

I have two datagrids in the other two columns. When the selected item in one of the datagrid changes the other datagrid changes it display values, i.e. a master detail template. This all works fine.

There is one value in the datagrid that if selected I wish this 3rd column to changes its width from zero to 2*. I don't know how to do this?

I wish to achieve this through XAML. I have been looking at data triggers & value converters. I written some code below quickly to test. I have read that setting the column to width=0 there is probably higher on the dependency property setting precedence list. Is there anyway to do this or will I need to use code behind?

 <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition Width="2*"/>
        <ColumnDefinition Width="0"/>
    </Grid.ColumnDefinitions>

    <DataGrid Grid.Column="0"
              ItemsSource="{Binding OrderList}"
              SelectedItem="{Binding OrderSelected}"                  
              AutoGenerateColumns="True">                                    
    </DataGrid>

    <TextBox Grid.Column="1" Text="{Binding OrderSelected.Name}">
    </TextBox>

    <Grid x:Name="columnHideSeek" Grid.Column="2" Background="Blue">
        <Grid.Style>
            <Style>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding OrderSelected.Name}" Value="Mark">
                        <Setter Property="Grid.Width" Value="10"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Style>
    </Grid>

</Grid>
like image 353
mHelpMe Avatar asked Dec 09 '13 16:12

mHelpMe


1 Answers

Using the correct DataTrigger, this is totally possible. First, add the Trigger to the UI element that you want to change... the ColumnDefinition, not the Grid:

<ColumnDefinition>
    <ColumnDefinition.Style>
        <Style TargetType="{x:Type ColumnDefinition}">
            <Setter Property="Width" Value="10" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding OrderSelected.Name}" Value="Mark">
                    <Setter Property="Width" Value="2*" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ColumnDefinition.Style>
</ColumnDefinition>

Next, don't set the Width on the ColumnDefinition element, but in the Style instead. Otherwise the Width on the ColumnDefinition element will override the value set from the DataTrigger.

like image 135
Sheridan Avatar answered Oct 27 '22 05:10

Sheridan