Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Changing column width at runtime

Tags:

c#

wpf

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?

EDIT

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 920
mHelpMe Avatar asked Jan 12 '23 18:01

mHelpMe


1 Answers

Your XAML file should looks like this:

<Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition Name="thirdColumn" Width="0"/>
    </Grid.ColumnDefinitions>
</Grid>

And selected datagrid event scope in your code behind file:

GridLength g2 = new GridLength(2, GridUnitType.Star);
thirdColumn.Width = g2;
like image 92
Zafer Ayan Avatar answered Jan 17 '23 22:01

Zafer Ayan