【问题标题】:WP7 usercontrol relative heightWP7 用户控件相对高度
【发布时间】:2011-09-21 16:56:28
【问题描述】:

我有一个网格,有几行。我有一个用户控件,我将它放在其中一行上,行跨度为 2。所有行都具有相同的高度。我将用户控件的垂直对齐设置为居中,因此它出现在两行的中间。我想要的是用户控件的网格行的高度为 1,而不管网格的高度如何。所以实际上用户控件的高度会相对于网格中行的高度增长,因为行高也是相对于网格高度的。

【问题讨论】:

  • 你的意思是标签是“WPF”吗?

标签: wpf windows-phone-7


【解决方案1】:

我首先认为通过公共属性将用户控件的高度数据绑定到行的高度可能会起作用,但是在我看来,您不能将行的高度绑定为 RowDefinition 子类 DependencyObject,但是 SetBinding 方法是在 FrameworkElement 中定义。

也就是说,一种选择可能是以编程方式查找行的高度并将控件高度绑定到该行。

示例属性

private int controlHeight;
public int ControlHeight
{
  get 
  {
     int row = Grid.GetRow(this.myControl);
     return myGrid.RowDefinitions[row].Height;
   }
   set
   {
       controlHeight = value;
       //Implement property changed event etc here if needed
    }
 } 

如果您想确保控件大小会动态缩放(加载时除外),则需要额外的代码来更新属性并通知 UI。您还可以检查网格的高度并除以此属性中的列数,尽管这可能无法扩展。

注意,因为您使用的是 colSpan,您可能需要将行高除以 2。

【讨论】:

    【解决方案2】:

    您可能希望将用户控件的高度数据绑定到 RowDefinition 的高度。这个问题有点相似,但他绑定的是行高,而不是包含的元素:How do I databind a ColumnDefinition's Width or RowDefinition's Height?

    我尝试了一种简单的方法,可能会不受欢迎,但可能适合您的需求。

    <Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
      <Grid ShowGridLines="True">  
        <Grid.RowDefinitions>
          <RowDefinition Height="1*"/>
          <RowDefinition Height="1*"/>
          <RowDefinition Height="1*"/>
          <RowDefinition Height="1*"/>
          <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>
    
        <Rectangle x:Name="measurementRect" VerticalAlignment="Stretch" Grid.Row="1" Fill="Blue" Width="1" Visibility="Hidden" />
        <Rectangle Grid.Row="2" Grid.RowSpan="2"
          VerticalAlignment="Center" Fill="Green" Height="{Binding ElementName=measurementRect,Path=ActualHeight}" Width="200" />
      </Grid>
    </Page>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      • 2012-05-06
      • 2017-04-07
      • 2010-11-25
      • 2011-08-06
      • 1970-01-01
      相关资源
      最近更新 更多