代码之家  ›  专栏  ›  技术社区  ›  George Sealy

将单个样式应用于多个控件(并调整每个样式)

  •  3
  • George Sealy  · 技术社区  · 16 年前

    目前,我正在为每个按钮创建一个新样式,这肯定不是最好的方法吗?

    2 回复  |  直到 13 年前
        1
  •  11
  •   Rhys    16 年前

    对于XAML唯一的解决方案,您可以考虑如下:

    我假设您使用控件模板作为样式的一部分,如下所示:-

    <Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type Button}">
            <Image x:Name="img" Style="{DynamicResource NormalImage}"/>
            <ControlTemplate.Triggers>
              <Trigger Property="IsEnabled" Value="false">
                <Setter Property="Source" TargetName="img" Value="Images\DisabledImage.png"/>
              </Trigger>
            </ControlTemplate.Triggers>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
    

    我在这里破坏了控制模板,你的可能更复杂

    现在,如果在与上述样式相同的区域中添加以下样式,则这将指定用于默认情况的图像

    <Style x:Key="NormalImage" TargetType="{x:Type Image}">
      <Setter Property="Source" Value="Images/DeafultImage.png"/>
    </Style>
    

    在XAML中,当需要使用按钮时,可以执行以下操作:-

    <Button Style="{DynamicResource MyButtonStyle}" >
      <Button.Resources>
        <Style x:Key="NormalImage" TargetType="{x:Type Image}">
          <Setter Property="Source" Value="Images/OverrideImage.png"/>
        </Style>
      </Button.Resources>
    </Button>
    

    它并不漂亮,但仍然允许使用主样式,并且比使用多个样式稍微短一些,复制更少。

    它的工作方式是首先在按钮的资源(通常为空)中搜索资源名“NormalImage”,然后搜索父容器,一直搜索到页面/窗口资源,再搜索到应用程序资源。第一个匹配项获胜,因此在本例中,引用OverrideImage.png的本地定义样式“NormalImage”被选在与引用DefaultImage.png同名的窗口/页面/容器级资源之前

    进一步减少文本的数量

    <Window.Resources>
      <Style x:Key="NormalImage" TargetType="{x:Type Image}">
        <Setter Property="Source" Value="Images/DeafultImage.png"/>
      </Style>
    
      <Style TargetType="{x:Type Button}">
        <Setter Property="Template">
                ...
        </Setter>
      </Style>
    </Window.Resources>
    
    <Button >
      <Button.Resources>
        <Style x:Key="NormalImage" TargetType="{x:Type Image}">
          <Setter Property="Source" Value="Images/OverrideImage.png"/>
        </Style>
      </Button.Resources>
    </Button>
    
    <Button Style="{x:null}>Normal Button</Button>
    
        2
  •  0
  •   justin.m.chase    16 年前

    您可以在ResourceDictionary中创建样式,然后将该字典合并到控件资源中。如果为样式指定键,则可以将任何按钮绑定到该样式。

    例如:

    <Style x:Key="imageButton" ControlType="{x:Type Button}">
        ...
    </Style>
    
    <Button Style="{DynamicResource imageButton}" />