WPF DataTrigger to display and hide grid column XA

2020-06-03 04:26发布

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>

1条回答
神经病院院长
2楼-- · 2020-06-03 04:43

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.

查看更多
登录 后发表回答