获取网格列Wpf的当前渲染宽度

时间:2019-01-23 11:36:21

标签: c# wpf

我有一个Grid,其中定义了一些列,并且列宽也在xaml中定义。

<Border Grid.Row="2" BorderThickness="2" BorderBrush="#001732"
        Width="{Binding ActualWidth, ElementName=ParentContainer}">
    <Grid Name="DataGrid" Width="{Binding ActualWidth, ElementName=ParentContainer}"
          Style="{StaticResource GridStyle}">

                    <ColumnDefinition Width="50*" />
                        <ColumnDefinition Width="50*" />
                        <ColumnDefinition Width="50*" />
                        <ColumnDefinition Width="50*" />
                        <ColumnDefinition Width="50*" />
                        <ColumnDefinition Width="50*" />
                        <ColumnDefinition Width="50*" />
                    </Grid.ColumnDefinitions>
     </Grid>
</Border>

现在,如果我更改窗口的大小,则列宽会自动更改。我正在尝试使用此代码获取更改的最新宽度。

public void CoulmnWidthSetter()
{
    _columnWidth = DataGrid.ColumnDefinitions[4].Width.Value;
    foreach (var col in DataGrid.ColumnDefinitions)
    {

        _totalColumnsWidth = _totalColumnsWidth + col.Width.Value;
    }
}  

,然后在事件下方调用列宽设置器方法。

private void ParentContainer_OnSizeChanged(object sender, SizeChangedEventArgs e)
    {
        CoulmnWidthSetter();
    } 

或者我也尝试在窗口大小更改事件中调用此方法。但是仍然总是给我那硬编码的50宽度值为什么?

1 个答案:

答案 0 :(得分:2)

在WPF中,WidthActualWidth是两件事。

您在这里寻找的是ActualWidth个中的ColumnDefinition

ActualWidth是一个double值,代表该时间点的长度。

签名:

public double ActualWidth { get; }

WidthGridLength类型;可以通过各种方式设置;包括硬编码值,星号值或自动。您可以设置Width(一种GridLength类型)来为ColumnDefinition提供所需的信息,以进行相应的动态调整或保持不变。它并不是要为您提供当前值,而是要为所有者提供一种富有表现力的方式来设置其值。

示例:

columnDefinition.Width = new GridLength(50); //Hard coded to 50

columnDefinition.Width = new GridLength(50, GridUnitType.Star); //dividend of remaining space allocated at 50.
//In other words; any other Star values will be divided in Width based on the remaining Grid size and the Star value given.
//A star value of 25* in another ColumnDefinition will make it half the length of the 50* and a value of 100* will make it twice the 50* or the 50* half of the 100*.
//Either way you look at it; the total remaining Width of the space provided by the panel gets divided out to the Star Columns and the dividend they get is based on their portion of the Star.  50* for all Columns will make them all equal.

columnDefinition.Width = GridLength.Auto; //Adjusts to the needed width dynamically.  As your content grows so does the Width.

Width也是DependencyProperty,因此它允许Binding,并且必须在UI线程上进行设置。

也;只是一个建议:您不必仅仅因为视图正在动态更改大小而以这种方式设置大小。这就是*星形在值设置中的含义。还有其他内置的方法可以执行此操作,但不确切知道为什么要执行此操作。有。