C# 动态设置网格列/行宽/高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9721001/
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-08-09 08:33:33  来源:igfitidea点击:

Set Grid Column/Row width/Height dynamically

c#wpfgridcode-behind

提问by Welsh King

I need to create a WPF grid dynamically from code behind. This is going okay and I can do it so that I set the content widths but what I need to do is set them so that when i resize the window the controls are re sized dynamically

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

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

This will produce XAML

这将产生 XAML

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

But what I need is to use a * or question mark ie.

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

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

But the WidthValue does not support a * or question mark a when creating from code behind ?

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

采纳答案by ionden

You could specify it like this:

你可以这样指定:

For auto sized columns:

对于自动调整大小的列:

GridLength.Auto

For star sized columns:

对于星型列:

new GridLength(1,GridUnitType.Star)

回答by Shounbourgh

I think this can help:

我认为这可以帮助:

for Auto Column:

对于自动列:

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

or for proportion grid length:

或比例网格长度:

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

or look at: http://msdn.microsoft.com/en-us/library/system.windows.gridlength.aspxand http://msdn.microsoft.com/en-us/library/system.windows.gridunittype.aspx

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

Greez Shounbourgh

格里兹松堡

回答by Jamaxack

There is 3 types of setting Width to Grid ColumnDefinitions:

有 3 种设置 Width 到 Grid ColumnDefinitions 的类型:

For Percentage Column:

对于百分比列:

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

In xaml:

在 xaml 中:

<ColumnDefinition Width="1*"/>

For Pixel Column

对于像素列

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

In xaml:

在 xaml 中:

<ColumnDefinition Width="10"/>

For Auto Column

对于自动列

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

In xaml:

在 xaml 中:

<ColumnDefinition Width="Auto"/>

Hope it helps!

希望能帮助到你!