我厌倦了一遍又一遍地创建相同的图像+文本按钮,我想将标记移动到控件模板。这是我的问题:我需要提供模板绑定来将图像和文本添加到模板化按钮,而Button控件似乎没有我可以绑定的属性。
到目前为止,我的模板看起来像这样(未知模板绑定的'???'):
<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>
是否可以使用控件模板创建此图像+文本按钮,还是必须转到用户控件才能执行此操作?如果可以使用控件模板完成,我该如何设置模板绑定?
答案 0 :(得分:31)
像这样定义一个CustomControl
<。3 中的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));
}
<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>