【问题标题】:Creating an image+text button with a control template?使用控件模板创建图像+文本按钮?
【发布时间】:2010-12-28 08:02:36
【问题描述】:

我厌倦了一遍又一遍地创建相同的图像+文本按钮,我想将标记移动到控件模板。这是我的问题:我需要提供模板绑定来将图像和文本添加到模板化按钮,而 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>

是否可以使用控件模板创建此图像+文本按钮,或者我必须转到用户控件来执行此操作?如果可以用控件模板完成,我该如何设置模板绑定?

【问题讨论】:

    标签: wpf controltemplate controltemplates


    【解决方案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>
    

    【讨论】:

    • 主题文件夹?什么主题文件夹?
    • @Qwertie - 当您在 WPF 中创建 CustomControl 时,Visual Studio 会自动将 Themes 文件夹添加到您的项目中以包含控件的可视化实现。
    • 这个解决方案对我有用,但我看不到默认按钮样式了。我想要的是拥有默认的按钮样式,以及图片和 TextBlock。
    猜你喜欢
    • 2010-11-18
    • 2013-02-16
    • 2017-11-16
    • 2012-05-29
    • 2011-09-08
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 2014-02-12
    相关资源
    最近更新 更多