Applying the same style to multiple controls (and customizing each style)

I have a WPF application using native style. In it, I have a set of buttons, each of which has a custom background image. For each button, I supply an image with a normal image and mouse. Is there an easy way to do this with one style (and customize each button in each case)?

I am currently creating a new style for each button, and this may not be the best way to do this for sure?

+3
source share
2 answers

For a XAML only solution, you can consider this: -

, : -

<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" ( ), , / . , , "NormalImage", OverrideImage.png, // , DefaultImage.png

, x: Key = "MyButtonStyle" . , WPF , . = "{x: null}", . : -

<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>
+11

ResourceDictionary, . , .

:

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

<Button Style="{DynamicResource imageButton}" />
0

All Articles