【问题标题】:WPF Style to all control of one UserControlWPF Style 对一个 UserControl 的所有控制
【发布时间】:2010-11-22 16:41:02
【问题描述】:

有没有办法动态地将样式应用于 one 用户控件中的所有相同类型的控件,而不应用到我的应用程序的所有控件中,也无需转到控件并手动设置样式?

编辑 问题是在我的 ResorceDictionary 中我有 2 种样式,其中 x:Key 集

<Style x:Key="ScrollBar_White" TargetType="{x:Type ScrollBar}">
<Style x:Key="ScrollBar_Black" TargetType="{x:Type ScrollBar}">

我想知道 XAML 中是否有一种方法可以动态应用命名样式,而无需在我的 UserControl 的所有滚动条上使用以下代码。

<ScrollBar Style="ScrollBar_White">

编辑

对不起,我是 WPF 的新手,所以我错过了让你知道一些重要的事情(我在应用你的最后一个解决方案后发现的)。 如果样式是 StaticResources,则最后一个解决方案实际上有效,但它们是 DynamicResources,并且 BasedOn 不适用于 DynamicResources。

任何想法如何使用 DynamicResource 做到这一点?

非常感谢,很抱歉我错过了问题中的重要点。

【问题讨论】:

    标签: wpf xaml styles


    【解决方案1】:

    是的,将其添加到相关控件的资源字典中。

    当您说“动态”时,我假设您指的是代码而不是 XAML。您可以在代码隐藏的用户控件上使用ResourceDictionary.Add 方法。

    这里有一些示例代码:

    public MyUserControl()
    {
        InitialiseComponent();
    
        var style = new Style(typeof(TextBlock));
        var redBrush = new SolidColorBrush(Colors.Red);
        style.Setters.Add(new Setter(TextBlock.ForegroundProperty, redBrush));
        Resources.Add(typeof(TextBlock), style);
    }
    

    这相当于(在 XAML 中):

    <UserControl.Resources>
      <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="Red" />
      </Style>
    </UserControl.Resources>
    

    因为没有x:Key 应用于样式,它被目标类型的所有实例拾取。在内部,类型本身被用作键(我相信)。

    编辑

    鉴于您的问题的更新,您似乎想要这个:

    <!-- this is the parent, within which 'ScrollBar_White' will be applied
         to all instances of 'ScrollBar' -->
    <StackPanel>
      <StackPanel.Resources>
        <Style TargetType="ScrollBar" BasedOn="{StaticResource ScrollBar_White}" />
      </StackPanel.Resources>
      <!-- scrollbars in here will be given the 'ScrollBar_White' style -->
    <StackPanel>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多