【问题标题】:How to bind Grid row height?如何绑定网格行高?
【发布时间】:2012-01-09 16:46:50
【问题描述】:

我有 2 个带有分离器的相同网格:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Button Grid.Row="0" />
    <Button Grid.Row="2" />
    <GridSplitter Grid.Row="1" Height="4" HorizontalAlignment="Stretch" />
</Grid>

如何让它们同步调整大小?这样两个网格的行高将相同。

【问题讨论】:

  • 它们是否相邻?
  • 它们位于 TabControl 的不同选项卡上

标签: c# .net wpf xaml data-binding


【解决方案1】:

看起来我可以通过简单的绑定做到这一点:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="{Binding Path=MySize, Mode=TwoWay}" />
        <RowDefinition Height="auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Button Grid.Row="0" />
    <Button Grid.Row="2" />
    <GridSplitter Grid.Row="1" Height="4" HorizontalAlignment="Stretch" />
</Grid>

MySize 在哪里

private GridLength mySize;
public GridLength MySize
{
    get { return mySize; }
    set
    {
        if (mySize == value) return;
        mySize = value;
        OnPropertyChanged("MySize");
    }
}

注意: Mode=TwoWay 是必需的,因为与其他控件不同,RowDefinition 不会默认其模式为 TwoWay

【讨论】:

    【解决方案2】:

    您需要使用Shared Size Groups。将属性SharedSizeGroup="some_label" 添加到要同步调整大小的行或列定义。

    此外,您需要为一些包含两个网格的容器定义Grid.IsSharedSizeScope="true"(在您的情况下为选项卡控件)。

    【讨论】:

    • Possibly relevant:"参与大小共享的列和行不遵守星号大小。在大小共享场景中,星号大小被视为自动"
    • 它的行为也很奇怪。当我在第一个选项卡中调整行大小时,我无法使其在其他选项卡中的大小小于第一个。
    • 我发现这是一个错误,导致此功能在我的情况下完全无用:connect.microsoft.com/VisualStudio/feedback/details/509801/…
    • 还有其他建议吗?也许将它们绑定到一些常见的 DependencyProperty?
    • @Poma 与Mode=TwoWay, UpdateSourceTrigger=PropertyChanged 绑定应该可以正常工作。只是不要忘记在属性设置器中引发 PropertyChanged 事件,否则第二个网格将不会被更新。
    【解决方案3】:

    我认为实现这一目标的唯一方法是编程:

    XAML 的两个网格中注册 Gridsplitter 的 DragCompleted 事件,并为每个网格命名:

    <GridSplitter DragCompleted="GridSplitter_DragCompleted1" Grid.Row="1" Height="4" HorizontalAlignment="Stretch" />
    

    CodeBehind 中同步 RowDefinitions 的高度。由于 grisplitter 只影响附加行/列的行/列定义,我们必须在此处同步行定义。设置 gridsplitters 位置等其他操作将不起作用。

    private void GridSplitter_DragCompleted1(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
    {
      SyncRowDefinitions(Grid1, Grid2);
    }
    
    private void GridSplitter_DragCompleted2(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
    {
      SyncRowDefinitions(Grid2, Grid1);
    }
    
    
    private void SyncRowDefinitions(Grid sourceGrid, Grid targetGrid)
    {
      for (int i = 0; i < sourceGrid.RowDefinitions.Count; i++)
      {
        targetGrid.RowDefinitions[i].Height = sourceGrid.RowDefinitions[i].Height;
      }
    }
    

    编辑:如果需要,您还可以在其他情况下同步网格,例如在初始加载后(整个网格的 sizechanged)等...

    【讨论】:

      猜你喜欢
      • 2011-04-23
      • 1970-01-01
      • 2017-12-04
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 2021-02-04
      • 2011-05-28
      相关资源
      最近更新 更多