【问题标题】:Set Grid Column/Row width/Height dynamically动态设置网格列/行宽/高
【发布时间】:2012-04-01 00:51:53
【问题描述】:

我需要从后面的代码动态创建一个 WPF 网格。这没关系,我可以这样做,以便我设置内容宽度,但我需要做的是设置它们,以便当我调整窗口大小时,控件会动态调整大小

var col = new ColumnDefinition();
col.Width = new System.Windows.GridLength(200);
grid1.ColumnDefinitions.Add(col);

这将产生 XAML

<Grid.ColumnDefinitions>
     <ColumnDefinition Width="200"></ColumnDefinition>
</Grid.ColumnDefinitions>

但我需要的是使用 * 或问号,即。

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

但是在从后面的代码创建时,WidthValue 不支持 * 或问号 a 吗?

【问题讨论】:

    标签: c# wpf grid code-behind


    【解决方案1】:

    你可以这样指定:

    对于自动调整大小的列:

    GridLength.Auto
    

    对于星形大小的列:

    new GridLength(1,GridUnitType.Star)
    

    【讨论】:

      【解决方案2】:

      Grid ColumnDefinitions 有 3 种设置宽度:

      百分比列:

       yourGrid.ColumnDefinitions[0].Width = new GridLength(1, GridUnitType.Star); 
      

      在 xaml 中:

      <ColumnDefinition Width="1*"/>
      

      对于像素列

      yourGrid.ColumnDefinitions[0].Width = new GridLength(10, GridUnitType.Pixel);
      yourGrid.ColumnDefinitions[0].Width = new GridLength(10); 
      

      在 xaml 中:

      <ColumnDefinition Width="10"/>
      

      对于自动列

      yourGrid.ColumnDefinitions[0].Width = GridLength.Auto;
      

      在 xaml 中:

      <ColumnDefinition Width="Auto"/>
      

      希望对你有帮助!

      【讨论】:

        【解决方案3】:

        我认为这会有所帮助:

        对于自动列:

        ColumnDefinition cd = new ColumnDefinition();
        cd.Width = GridLength.Auto;
        

        或比例网格长度:

        ColumnDefinition cd = new ColumnDefinition();
        cd.Width = new GridLength(1, GridUnitType.Star);
        

        或查看: http://msdn.microsoft.com/en-us/library/system.windows.gridlength.aspx 和 http://msdn.microsoft.com/en-us/library/system.windows.gridunittype.aspx

        格力兹 肖恩堡

        【讨论】:

          猜你喜欢
          • 2018-09-03
          • 2016-06-23
          • 1970-01-01
          • 1970-01-01
          • 2016-10-19
          • 1970-01-01
          • 1970-01-01
          • 2020-09-15
          • 2012-09-29
          相关资源
          最近更新 更多