C# 如何以百分比设置 XAML 宽度?

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

How to set XAML Width in percentage?

c#.netvisual-studioxamlwidth

提问by Tom

I am trying to create a button in XAML with a 80% width, but I can't seem to figure out how. It's apparently not as easy as using Width="80%". I have been thinking this can be done by detecting the screen width somehow and multiply that by 0.8 and use that as the width, but I am not sure how I can do this in XAML. Perhaps this has to be done in the .cs file and then adjust the width from there. Does anyone have a solution for this?

我正在尝试在 XAML 中创建一个宽度为 80% 的按钮,但我似乎无法弄清楚如何。这显然不像使用 Width="80%" 那样容易。我一直认为这可以通过以某种方式检测屏幕宽度并将其乘以 0.8 并将其用作宽度来完成,但我不确定如何在 XAML 中执行此操作。也许这必须在 .cs 文件中完成,然后从那里调整宽度。有没有人对此有解决方案?

采纳答案by Fendy

Is it WPF?

是WPF吗?

If yes, then wrap your control (button) in grid. Then specify the grid column definition. Example:

如果是,则将您的控件(按钮)包裹在网格中。然后指定网格列定义。例子:

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="0.2*"></ColumnDefinition>
    <ColumnDefinition Width="0.8*"></ColumnDefinition>
  </Grid.ColumnDefinitions>
  <Button Grid.Column="1" Grid.Row="0"></Button>
</Grid>

Edit:Forget to close <Button>tag.

编辑:忘记关闭<Button>标签。

回答by Sheraz Ahmed

I think the more proper way would be

我认为更合适的方法是

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="2*"></ColumnDefinition>
    <ColumnDefinition Width="10*"></ColumnDefinition>
  </Grid.ColumnDefinitions>
  <Button Grid.Column="1" Grid.Row="0"></Button>
</Grid>

12 grid distribution like bootstrap, it's just about your preference

12种类似bootstrap的网格分布,随你喜好