创建带有控件模板的图像+文本按钮? [英] Creating an image+text button with a control template?
问题描述
我厌倦了一次又一次地创建相同的图像+文本按钮,我想将标记移至控件模板.这是我的问题:我需要提供模板绑定,以将图像和文本添加到模板化按钮上,并且Button控件似乎没有可以绑定的属性.
I am tired of creating the same image+text button over and over again, and I would like to move the markup to a control template. Here is my problem: I need to provide template bindings to add the image and text to the templated button, and the Button control doesn't seem to have properties that I can bind to.
到目前为止,我的模板看起来像这样(对于未知的模板绑定,带有"???"):
My template looks like this so far (with '???' for the unknown template bindings):
<ControlTemplate x:Key="ImageButtonTemplate" TargetType="{x:Type Button}">
<StackPanel Height="Auto" Orientation="Horizontal">
<Image Source="{TemplateBinding ???}" Width="24" Height="24" Stretch="Fill"/>
<TextBlock Text="{TemplateBinding ???}" HorizontalAlignment="Left" Foreground="{DynamicResource TaskButtonTextBrush}" FontWeight="Bold" Margin="5,0,0,0" VerticalAlignment="Center" FontSize="12" />
</StackPanel>
</ControlTemplate>
是否可以使用控件模板来创建此图像+文本按钮,还是我必须转到用户控件才能执行此操作?如果可以通过控制模板完成,该如何设置模板绑定?
Is it possible to create this image+text button using a control template, or do I have to go to a user control to do it? If it can be done with a control template, how do I set up the template bindings?
推荐答案
定义这样的CustomControl
Define a CustomControl like this
public class MyButton : Button
{
static MyButton()
{
//set DefaultStyleKeyProperty
}
public ImageSource ImageSource
{
get { return (ImageSource)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
// Using a DependencyProperty as the backing store for ImageSource. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(MyButton), new UIPropertyMetadata(null));
}
在主题文件夹的generic.xaml中
<Style TargetType="{x:Type MyButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MyButton}">
<StackPanel Height="Auto" Orientation="Horizontal">
<Image Source="{TemplateBinding ImageSource}" Width="24" Height="24" Stretch="Fill"/>
<TextBlock Text="{TemplateBinding Content}" HorizontalAlignment="Left" Foreground="{DynamicResource TaskButtonTextBrush}" FontWeight="Bold" Margin="5,0,0,0" VerticalAlignment="Center" FontSize="12" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
这篇关于创建带有控件模板的图像+文本按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!