WPF样式可以控制一个UserControl

Pau*_*ulo 3 wpf xaml styles

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

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

<Style x:Key="ScrollBar_White" TargetType="{x:Type ScrollBar}">
<Style x:Key="ScrollBar_Black" TargetType="{x:Type ScrollBar}">
Run Code Online (Sandbox Code Playgroud)

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

<ScrollBar Style="ScrollBar_White">
Run Code Online (Sandbox Code Playgroud)

编辑

对不起,我是WPF的新手,所以我很想让你知道一些重要的事情(我在应用你的最后一个解决方案后发现).如果样式是StaticResources,则最后一个解决方案实际上有效,但它们是DynamicResources,而BasedOn与DynamicResources不兼容.

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

非常感谢,对不起,我错过了我的问题中的重点.

Dre*_*kes 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);
}
Run Code Online (Sandbox Code Playgroud)

这相当于(在XAML中):

<UserControl.Resources>
  <Style TargetType="TextBlock">
    <Setter Property="Foreground" Value="Red" />
  </Style>
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)

由于没有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>
Run Code Online (Sandbox Code Playgroud)