如何在资源字典中基于另一个样式创建样式?

28

我有一个应用于资源字典中所有按钮的主题。现在我想为按钮添加一个触发器,同时继承字典中的样式更改。我尝试了下面的代码,但它说找不到控件。我该如何解决?

<UserControl.Resources>
  <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="Theme.xaml"/>
      </ResourceDictionary.MergedDictionaries>

      <conv:ErrorContentConverter x:Key="ErrorContentConverter" />

      <Style x:Key="ValidTrigger" 
             TargetType="Control" BasedOn="{StaticResource {x:Type Control}}">
         <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsValid}" Value="False">
              <Setter Property="IsEnabled" Value="false" />
            </DataTrigger>
         </Style.Triggers>
      </Style>   
  </ResourceDictionary>
</UserControl.Resources>

基础模板:

    <Style TargetType="{x:Type Button}" BasedOn="{x:Null}">
    <Setter Property="FocusVisualStyle" 
            Value="{DynamicResource NuclearButtonFocusVisual}" />
    <Setter Property="Foreground" Value="#FF042271" />
    <Setter Property="FontFamily" Value="Trebuchet MS" />
    <Setter Property="FontSize" Value="12" />
    <Setter Property="Padding" Value="3" />

    <Setter Property="Template" Value="{DynamicResource ButtonTemplate}" />
</Style>
3个回答

36

我过去使用的一个技巧是:在定义应用程序的全局样式的 ResourceDictionary 中,为想要继承的样式添加一个 x:Key,如下所示:

<Style TargetType="{x:Type Button}" x:Key="ButtonStyle">
  <!-- your style here -->
</Style>

为了将此样式应用于指定类型的所有控件(例如此处的

32

给你的基础样式起一个名字,比如说FooStyle。

在你提供的示例中,将TargetType和BasedOn修改为以下内容:

 <Style x:Key="ValidTrigger" 
        TargetType="{x:Type Control}" BasedOn="{StaticResource {x:Type Control}}" >
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=IsValid}" Value="False">
            <Setter Property="IsEnabled" Value="false" />
        </DataTrigger>
    </Style.Triggers>
</Style>

我可以不给它指定一个名称吗?字典中的控件只有一种样式。 - Marcom
你的意思是,与其为基本样式分配一个键,你希望扩展样式根据它的TargetType来确定要扩展哪个样式?我不知道。 - Pieter Müller
为什么你犹豫不决地不给基础样式一个x:Key="FooStyle"? - Pieter Müller
3
如果您给样式分配一个键,那么该样式将不再默认用于上下文中所有匹配的控件。Nathan Friend的答案为此提供了解决方案。我刚遇到了同样的问题 :) - OregonGhost

3
我认为“控件”没有定义基本样式,所以你的BasedOn="{StaticResource {x:Type Control}}"部分找不到任何东西。
你可能想要更改。
<Style x:Key="ValidTrigger" TargetType="Control" BasedOn="{StaticResource {x:Type Control}}" >

to

<Style x:Key="ValidTrigger" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}" >

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