【问题标题】:WPF: Binding the height of a component to another'sWPF:将组件的高度绑定到另一个组件的高度
【发布时间】:2011-01-15 00:24:10
【问题描述】:

我在一个窗口中有一个Grid,其中包含一个RadioButton、一个TextBox 和一个Button,分别位于第0、1、2 列。它们的高度都设置为自动。

然后,在窗口的另一部分,我在第 0、1 和 2 列中有另一个 GridLabelTextBoxButton。高度也设置为自动。

我遇到的问题是第一个网格的高度小于第二个网格的高度。我想这是因为标签迫使第二个更高。我怎样才能使第一个网格与第二个网格一样高?我试过这样做:

将第二个网格中的文本框命名为 SomeName。
在第一个网格的<Grid.ColumnDeclarations> 中,我将高度从“auto”更改为“{Binding ElementName=SomeName, Path=Height}”。

但这并没有达到我想要的效果。大小是一样的。我猜 Binding 基本上是“自动”并把它扔在那里,这最终是同一件事。

另外,我正在寻找一种不涉及将高度设置为固定值的解决方案。

【问题讨论】:

    标签: wpf xaml data-binding height


    【解决方案1】:

    绑定到ActualHeight 而不是Height 属性:

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

    【讨论】:

    • 那也没用。我让它工作的唯一方法是添加标签并隐藏它。啊。
    • 很好奇。我在发布之前确实对其进行了测试,尽管使用的是 TextBlock 而不是 TextBox。可能是网格添加的边距问题(我想绑定到另一个 RowDefinition 的 ActualHeight 以避免这个问题,但这不起作用)。
    • 我认为应该是&lt;RowDefinition Height="{Binding Path=ActualHeight, ElementName=otherTextBox}" /&gt;
    【解决方案2】:

    将两个网格放在shared size 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>
    

    另请参阅 MSDN 中的 How to: Share sizing properties between grids

    【讨论】:

      猜你喜欢
      • 2012-10-16
      • 2011-06-08
      • 2022-12-18
      • 2018-03-02
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      相关资源
      最近更新 更多