tags:

views:

152

answers:

2

There are multiple places in my WPF application where I need a button that looks & feels like a regular button, but:

  1. It shows a specific icon on it (defined as {StaticResource EditIcon})
  2. It applies a style (defined as {StaticResource GrayOutButtonStyle})

I would prefer to define these attributes in a single location, rather than repeating them each place the button is used. What is the appropriate way to do this in XAML?

--

If it helps, below is what I'm currently doing, but I was told this is wrong:

Updated: Is this the wrong way? Is there a way to fix this so that it is the "right way"?

I define the button as a template with the key EditButton:

<ControlTemplate x:Key="EditButton" TargetType="{x:Type Button}">
     <Button Style="{StaticResource GrayOutButtonStyle}" 
             Command="{TemplateBinding Command}">
        <Image x:Name="editImage" Source="{StaticResource EditIcon}" />
     </Button>
</ControlTemplate>

Then, I declare a button with the template EditButton each place I want to use it in the application. I also indicate the Command to invoke here:

<Button Template="{StaticResource EditButton}" Command="..." />

Is this not right? What would be the correct way to do this?

A: 

A different approach:

Have you considered making a custom control? This way, you can create your own attributes to set the image contained in the button, and don't have to rely on multiple styles.

<myControl:MyButton x:Name="oneButton" ImageSource="MyButton.png" />
<myControl:MyButton x:Name="anotherButton" ImageSource="MyOtherButton.png" />

class MyButton {

  private string imageSource;
  public string ImageSource {
    get {
      return this.imageSource;
    }
    set {
      this.imageSource = value;
      //set the image control's source to this.imageSource
    }
  }
}
AlishahNovin
A: 

You can create a Style which targets all the Button of your app. Do do that, simply create a Style without giving it a Key:

<Style TargetType={x:Type Button}>
</Style>

Then in the Style, you can add a setter which sets the Template property:

<Setter Property="Template">
  <Setter.Value>
    <!-- whatever you want -->
  </Setter.Value>
</Setter>
Jalfp
Abby Fichtner
You can change the ControlTemplate to include an image somewhere in the tree. For example you can use a grid with 2 columns, put the image in the first column, and a ContentPresenter in the second one.
Jalfp