WPF: Binding the height of a component to another's

你说的曾经没有我的故事 提交于 2019-12-20 11:22:51

问题


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.

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.

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:

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}".

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.


回答1:


Put the two grids in a shared size scope, and use SharedSizeGroup to lock the row heights together:

<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 grids in MSDN.




回答2:


Bind to the ActualHeight rather than the Height property:

<RowDefinition Height="{Binding ActualHeight, ElementName=otherTextBox}" />


来源:https://stackoverflow.com/questions/2232675/wpf-binding-the-height-of-a-component-to-anothers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!