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

Я устал от создания той же image+text кнопки много раз, и я хотел бы переместить разметку в шаблон управления. Вот моя проблема: Я должен обеспечить шаблонную привязку для добавления изображения и текста к шаблонной кнопке, и Кнопочное управление, кажется, не имеет свойства, с которыми я могу связать.

Мой шаблон похож на это до сих пор (с'???' для неизвестной шаблонной привязки):

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

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

15
задан David Veeneman 19 December 2009 в 15:05
поделиться

1 ответ

Define a CustomControl like this

in .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));
}

in 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>
31
ответ дан 1 December 2019 в 02:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: