Подтвердить что ты не робот

Создание кнопки изображения + текста с шаблоном управления?

Я устал от создания одной и той же кнопки изображения + текста снова и снова, и я хотел бы переместить разметку на шаблон управления. Вот моя проблема: мне нужно предоставить привязки шаблонов, чтобы добавить изображение и текст к шаблонной кнопке, а элемент управления 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>

Возможно ли создать эту картинку + текстовую кнопку с помощью шаблона управления или мне нужно перейти к пользовательскому элементу управления? Если это можно сделать с помощью шаблона управления, как мне настроить привязки шаблонов?

4b9b3361

Ответ 1

Определите 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>