使用控件模板创建带图像和文本的按钮?

15

我已经厌倦了一遍又一遍地创建相同的图像+文本按钮,我想将标记移动到控件模板中。这是我的问题:我需要提供模板绑定以将图像和文本添加到模板化的按钮中,但按钮控件似乎没有可绑定的属性。

到目前为止,我的模板看起来像这样(使用“???”表示未知的模板绑定):

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

我是否可以使用控件模板来创建这种图像+文本按钮,或者必须使用用户控件来实现?如果可以使用控件模板,请问如何设置模板绑定?

1个回答

32

像这样定义一个CustomControl

在 .cs 文件中

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>

主题文件夹?什么主题文件夹? - Qwertie
2
@Qwertie - 当你在WPF中创建自定义控件时,Visual Studio会自动将一个Themes文件夹添加到你的项目中,以包含你的控件的视觉实现。 - viky
1
这个解决方案对我有用,但是我不再看到默认的按钮样式了。我想要的是具有默认按钮样式的图像和TextBlock。 - Climooo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接