Creating an image+text button with a control template?

被刻印的时光 ゝ 提交于 2019-11-26 11:03:24

问题


I am tired of creating the same image+text button over and over again, and I would like to move the markup to a control template. Here is my problem: I need to provide template bindings to add the image and text to the templated button, and the Button control doesn\'t seem to have properties that I can bind to.

My template looks like this so far (with \'???\' for the unknown template bindings):

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

Is it possible to create this image+text button using a control template, or do I have to go to a user control to do it? If it can be done with a control template, how do I set up the template bindings?


回答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 of themes folder

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


来源:https://stackoverflow.com/questions/1933127/creating-an-imagetext-button-with-a-control-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!