如果无法通过样式设置子控件属性,如何通过 XAML 设置子控件属性

问题描述 投票:0回答:1

我想在用户控件中设置子控件的属性。

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="auto"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="auto"/>
    </Grid.ColumnDefinitions>
    <Label Grid.Column="0" x:Name="cLabel" Content="{Binding Caption}" />
    <TextBox Grid.Column="1" x:Name="cTextBox" Text="{Binding Text}"/>
    <Label Grid.Column="2" x:Name="cUnit" Content="{Binding Unit}"/>
</Grid>

<!-- how to set only cLabel Width? something like: -->
<local:LabeledTextbox cLabel.Width=100>

我想它不可能通过样式,因为样式也会设置

cUnit
。对吗?

我尝试了样式,但它设置了所有子项。

c# wpf xaml
1个回答
0
投票

您可以使用该元素的资源来设置这些属性。

        <local:LabeledTextbox>
            <local:LabeledTextbox.Resources>
                <Style TargetType="Label">
                    <Setter Property="Width" Value="100" />
                    <Setter Property="BorderBrush" Value="Gray" />
                    <Setter Property="BorderThickness" Value="1" />
                    <Setter Property="Margin" Value="4" />
                    <Setter Property="Foreground" Value="Purple" />
                    <Setter Property="FontStyle" Value="Italic" />
                </Style>
            </local:LabeledTextbox.Resources>
        </local:LabeledTextbox>

或者,如果您想为多个控件设置该值,您可以将要隔离的内容块包装在某种容器控件中,并为包含元素设置资源,如下所示:

        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="auto" />
            </Grid.ColumnDefinitions>
            <Label Grid.Column="0" x:Name="cLabel" Content="Caption" />
            <TextBox Grid.Column="1" x:Name="cTextBox" Text="Text" />
            <Label Grid.Column="2" x:Name="cUnit" Content="Unit" />
        </Grid>

        <StackPanel>
            <StackPanel.Resources>
                <Style TargetType="Label">
                    <Setter Property="Width" Value="100" />
                    <Setter Property="BorderBrush" Value="Gray" />
                    <Setter Property="BorderThickness" Value="1" />
                    <Setter Property="Margin" Value="4" />
                    <Setter Property="Foreground" Value="Purple" />
                    <Setter Property="FontStyle" Value="Italic" />
                </Style>
            </StackPanel.Resources>
            <local:LabeledTextbox />
            <local:LabeledTextbox />
            <local:LabeledTextbox />
        </StackPanel>

© www.soinside.com 2019 - 2024. All rights reserved.