15

同じ画像とテキストのボタンを何度も作成するのにうんざりしているため、マークアップをコントロール テンプレートに移動したいと考えています。ここに私の問題があります: テンプレート化されたボタンに画像とテキストを追加するためにテンプレート バインディングを提供する必要がありますが、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>

コントロール テンプレートを使用してこのイメージ + テキスト ボタンを作成することは可能ですか、それともユーザー コントロールに移動する必要がありますか? コントロール テンプレートで実行できる場合、テンプレート バインディングを設定するにはどうすればよいですか?

4

1 に答える 1

31

このように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>
于 2009-12-19T15:16:44.783 に答える