WPF 在运行时更改列宽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20443642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:10:25  来源:igfitidea点击:

WPF Changing column width at runtime

c#wpfxaml

提问by mHelpMe

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.

我有一个包含网格的 WPF 应用程序。网格被分成 3 列,加载时第三个网格的宽度为零。

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?

数据网格中有一个值,如果选中,我希望第三列的宽度从零更改为 2*。我不知道如何做到这一点?

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?

我希望通过 XAML 实现这一点。我一直在研究数据触发器和值转换器。我在下面快速编写了一些代码进行测试。我读过将列设置为 width=0 可能更高的依赖属性设置优先级列表。无论如何要做到这一点还是我需要使用背后的代码?

 <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>

回答by Zafer Ayan

Your XAML file should looks like this:

您的 XAML 文件应如下所示:

<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;