WPF: How do I create a button "template" that applies a style & has an image in it?
There are multiple places in my WPF application where I need a button that looks & feels like a regular button, but:
- It shows a specific icon on it (defined as
{StaticResource EditIcon}
) - 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 开发者_StackOverflow社区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 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
}
}
}
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>
精彩评论