【问题标题】:Style usercontrol child by name in XAML?在 XAML 中按名称样式化用户控件子项?
【发布时间】:2017-06-23 08:11:28
【问题描述】:

我在stackoverflow中看到了如下代码:

   <UserControl x:Class="WpfApplication3.UserControl1"
                 x:Name="Uc1"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <UserControl.Resources>
            <Style TargetType="Label">
                <Setter Property="Foreground"
                        Value="{Binding Foreground, ElementName=Uc1, Mode=OneWay}"/>
            </Style>
        </UserControl.Resources>

        <Grid>            
            <Label Content="Label 1"/>
            <Label Content="Label 2"/>
        </Grid>
    </UserControl>

问题:我现在想知道是否可以针对我的 usercontrol.resources 中的特定标签进行样式设置。我的userControl里面有可能吗?如果是那怎么办?

【问题讨论】:

    标签: c# wpf xaml user-controls


    【解决方案1】:

    没有Key 的样式将应用于范围内目标类型的所有实例。

    给样式一个Key,喜欢,

    <Style TargetType="Label" x:Key="MyLabel">
    

    然后按如下方式使用密钥

    <Label Content="Label 1" Style="{StaticResource MyLabel}" />
    
    <!--Will not apply the style to Label 2-->
    <Label Content="Label 2"/> 
    

    编辑:

    我再次阅读了您的问题,您似乎想从Style 引用Target,而不是从Target 引用Style。那正确吗?这听起来不自然,就像想从基类中知道派生类实例的名称。

    【讨论】:

    • 接受你的回答:)
    猜你喜欢
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    相关资源
    最近更新 更多