WPF:将组件的高度绑定到另一个组件的高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2232675/
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
WPF: Binding the height of a component to another's
提问by zxcvbnm
I have, in a window, a Grid
that contains a RadioButton
, a TextBox
and a Button
, each in column 0, 1, 2, respectively. They all have their heights set to auto.
我在一个窗口中有一个Grid
包含 a RadioButton
、 aTextBox
和 a 的 a Button
,分别位于第 0、1、2 列。它们的高度都设置为自动。
Then, in another part of the window, I have another Grid
with a Label
, a TextBox
and a Button
, in columns 0, 1, and 2. Heights are also set to auto.
然后,在窗口的另一部分,我在第 0、1 和 2 列中还有另一个Grid
带有 a Label
、 aTextBox
和 a Button
。高度也设置为自动。
The problem I have is that the first grid's height is smaller than the second's. I guess it's because Label is forcing the second one to be taller. How can I make it so that the first grid is as tall as the second? I tried doing this:
我的问题是第一个网格的高度小于第二个网格的高度。我想这是因为 Label 迫使第二个更高。我怎样才能使第一个网格与第二个网格一样高?我尝试这样做:
Name the textbox in the second grid SomeName.
In the <Grid.ColumnDeclarations>
of the first Grid, I changed Height from "auto" to "{Binding ElementName=SomeName, Path=Height}".
将第二个网格中的文本框命名为 SomeName。
在<Grid.ColumnDeclarations>
第一个网格中,我将高度从“自动”更改为“{Binding ElementName=SomeName, Path=Height}”。
But that didn't do what I wanted. The size was the same. I guess the Binding is basically getting "auto" and throwing it there, which ends up being the same thing.
但这并没有达到我想要的效果。大小是一样的。我猜绑定基本上是“自动”并将其扔到那里,结果是一样的。
Also, I'm looking for a solution that doesn't involve setting the heights to a fixed value.
另外,我正在寻找一种不涉及将高度设置为固定值的解决方案。
采纳答案by itowlson
Put the two grids in a shared size scope, and use SharedSizeGroup
to lock the row heights together:
将两个网格放在共享大小 scope 中,并用于SharedSizeGroup
将行高锁定在一起:
<SomeContainer Grid.IsSharedSizeScope="True"> <!-- Could be the Window or some more nearby Panel -->
<Grid>
<Grid.RowDefinitions>
<RowDefinition SharedSizeGroup="LabelAndRadioButtonGroup" />
</Grid.RowDefinitions>
<Label Grid.Row="0" />
</Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition SharedSizeGroup="LabelAndRadioButtonGroup" />
</Grid.RowDefinitions>
<RadioButton Grid.Row="0" />
</Grid>
</SomeContainer>
See also How to: Share sizing properties between gridsin MSDN.
另请参见如何:在 MSDN 中的网格之间共享大小属性。
回答by itowlson
Bind to the ActualHeight
rather than the Height
property:
绑定到ActualHeight
而不是Height
属性:
<RowDefinition Height="{Binding ActualHeight, ElementName=otherTextBox}" />