WPF样式应用于一个UserControl中的所有控件

3
有没有一种方法可以动态地将样式应用于同一类型的所有控件中的一个用户控件,而不必在我的应用程序中的所有控件上应用,并且不必手动设置样式? 编辑: 问题在于我的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很陌生,所以我忘记告诉你一些非常重要的事情(在应用了你的最后一个解决方案后发现的)。 如果样式是DynamicResources,则上一个解决方案实际上是可行的,但是从DynamicResources继承BasedOn不起作用。

有什么方法可以使用DynamicResource实现此功能吗?

非常感谢,并且很抱歉我在问题中遗漏了重要点。

1个回答

7

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

当您说“动态”时,我认为您指的是在代码中而不是在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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接