WPF中的网格调整大小问题

时间:2013-04-03 19:18:41

标签: wpf resize grid

我发现了一件事,我真的无法理解。 使用网格,列和行构建一些数据表。想尝试一些WPF元素.. 外部有“Wrapper”Grid,内部是Grid,包含列和行。 在后面的代码中,我正在改变Grid列的宽度,具体取决于窗口大小 - 在OnRenderSizeChanged中调用调整大小的方法。第一列应该仍然是相同的宽度。 事情是 - 当我展开窗口时,列完美地调整大小,但是当我缩回窗口时,列不会改变,因为内部网格宽度保持不变并且不会改变... 就是这样,我想问一下为什么会发生这种情况,为什么内部网格不会改变?

  

XAML

<Window x:Class="Csharp_and_WPF_testing.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="700" Width="696" MinWidth="696">
<Grid Name="main" >

    <Grid Name="view_Wrapper" Margin="15,250,15,15" Background="Silver">
        <Grid Name="view_ContentPresenter" Margin="0" ShowGridLines="True" >
            <Grid.ColumnDefinitions>
                <ColumnDefinition Name="MENU"/>
                <ColumnDefinition Name="Id"/>
                <ColumnDefinition Name="Name"/>
                <ColumnDefinition Name="Spec"/>
                <ColumnDefinition Name="Info"/>
            </Grid.ColumnDefinitions>
        </Grid> 
    </Grid>
    <Label Name="lb" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="276,65,0,0" Width="179"/>
</Grid>

  

代码背后

protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
    {
        base.OnRenderSizeChanged(sizeInfo);
        if (sizeInfo.WidthChanged) PrintColumns();
    }


    private void PrintColumns()
    {
        lb.Content = "Presenter width: "+view_ContentPresenter.ActualWidth + Environment.NewLine + "Wrapper width: "+view_Wrapper.ActualWidth;

        view_ContentPresenter.ColumnDefinitions[0].Width = new GridLength(30);

        for (int i = 1; i < view_ContentPresenter.ColumnDefinitions.Count; i++)             
        {
            view_ContentPresenter.ColumnDefinitions[i].Width = new GridLength(50);
        }


        double totalColsWidth = 0;                // sum of columns widths apart from first still same column
        for (int i = 1; i < view_ContentPresenter.ColumnDefinitions.Count; i++) totalColsWidth += view_ContentPresenter.ColumnDefinitions[i].Width.Value;

       double resW = view_ContentPresenter.ActualWidth - view_ContentPresenter.ColumnDefinitions[0].Width.Value;

        if (totalColsWidth < resW)        // if totalcolwidth is smaller than space left in contentPresenter grid then it is resized using ratio
        {
            double ratio = resW / totalColsWidth;

            for (int i = 1; i < view_ContentPresenter.ColumnDefinitions.Count; i++)
            {
                    view_ContentPresenter.ColumnDefinitions[i].Width = new GridLength(50 * ratio);
            }
        }
    }

感谢您的任何建议......(代码仅用于示例目的,我知道它可以通过其他方式解决)

0 个答案:

没有答案