簡體   English   中英

在資源中按樣式指定Grid列和行定義

[英]Specifying Grid column and row definition by style in resource

有一個帶有以下網格的UserControl:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
</Grid>

現在我有一個窗口,我會寫這樣的東西:

<Window.Resources>
    <Style TargetType="Grid">
        <Setter Property="RowDefinitions">
            <Value>
                <RowDefinition Height="*"/>
                <RowDefinition/>
            </Value>
        </Setter>
    </Style>
</Window.Resources>

關鍵部分,不編譯是我想要將高度從自動更改為*。 如何以合法的方式做到這一點?

一般來說,我必須處理案件。 1)第一行應拉伸,第二行應固定。 2)反之亦然。 也許與Grid不同的面板可能更相關?

Grid.RowDefinitionsGrid.ColumnDefinitions不是依賴項屬性,因此不能由Style設置。

您可以在UserControl中創建依賴項屬性FirstRowHeight ,並將第一個RowDefinitionHeight綁定到該屬性。 稍后您可以在Style設置FirstRowHeight屬性。

<Grid.RowDefinitions>
    <RowDefinition Height="{Binding FirstRowHeight,
        RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"/>
    <RowDefinition/>
</Grid.RowDefinitions>

該屬性將如下所示:

public static readonly DependencyProperty FirstRowHeightProperty =
    DependencyProperty.Register(
        "FirstRowHeight", typeof(GridLength), typeof(YourUserControl));

public GridLength FirstRowHeight
{
    get { return (GridLength)GetValue(FirstRowHeightProperty); }
    set { SetValue(FirstRowHeightProperty, value); }
}

編輯:為了支持您在問題結尾處描述的簡單場景,您可能還有一個IsFirstRowFixed依賴項屬性,其屬性已更改回調,用於設置代碼中的行高:

<Grid.RowDefinitions>
    <RowDefinition x:Name="row1" Height="*"/>
    <RowDefinition x:Name="row2" Height="Auto"/>
</Grid.RowDefinitions>

財產:

public static readonly DependencyProperty IsFirstRowFixedProperty =
    DependencyProperty.Register(
        "IsFirstRowFixed", typeof(bool), typeof(UserControl2),
        new PropertyMetadata((o, e) => ((UserControl2)o).IsFirstRowFixedChanged()));

public bool IsFirstRowFixed
{
    get { return (bool)GetValue(IsFirstRowFixedProperty); }
    set { SetValue(IsFirstRowFixedProperty, value); }
}

private void IsFirstRowFixedChanged()
{
    if (IsFirstRowFixed)
    {
        row1.Height = GridLength.Auto;
        row2.Height = new GridLength(1, GridUnitType.Star);
    }
    else
    {
        row1.Height = new GridLength(1, GridUnitType.Star);
        row2.Height = GridLength.Auto;
    }
}

XAML代碼:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="auto"/>
    </Grid.RowDefinitions>
<Grid Grid.Row="1" Style="{StaticResource HeaderHeight}"</>
<Grid Grid.Row="1" Style="{StaticResource FooterHeight}"</>
</>

資源字典中的樣式

<Style TargetType="Frame" x:Name="HeaderHeight">
    <Setter Property="Height" Value="700"></Setter>
</Style>
<Style TargetType="Grid" x:Name="FooterHeight">
    <Setter Property="Height" Value="70"></Setter>
</Style>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM