wpf - WPF中的自定义按钮模板

标签 wpf custom-controls styles

我想创建一个简单的按钮模板,其中包含图像和文本。但是我想保持系统按钮的外观。

如何逐步创建它?

附注:我已经在WPF和CustomControl属性中使用BasedOn进行了尝试。

最佳答案

您可以使用样式和附加属性轻松完成此操作:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ap="clr-namespace:MyProject.Namespace.Path.To.ButtonProperties">
    ...
    <Style x:Key="ImageButton" TargetType="Button">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="{Binding Path=(ap:ButtonProperties.Image), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}"></Image>
                        <ContentPresenter Content="{Binding Path=Content, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}"></ContentPresenter>
                    </StackPanel>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    ...
</ResourceDictionary>




public class ButtonProperties
{
    public static ImageSource GetImage(DependencyObject obj)
    {
        return (ImageSource)obj.GetValue(ImageProperty);
    }

    public static void SetImage(DependencyObject obj, ImageSource value)
    {
        obj.SetValue(ImageProperty, value);
    }

    public static readonly DependencyProperty ImageProperty =
        DependencyProperty.RegisterAttached("Image", typeof(ImageSource), typeof(ButtonProperties), new UIPropertyMetadata((ImageSource)null));
}


然后在标记中:

<Button Style="{StaticResource ImageButton}" ap:ButtonProperties.Image="{StaticResource MyImage}" Content="Test">
</Button>


这个例子看起来很可怕,但是您可以轻松地将StackPanel更改为Grid或类似的方法来限制图像比例。使用ContentPresenter可以保留按钮的行为,允许您将任何UIElement放入其中,并保留Command的支持等。

关于wpf - WPF中的自定义按钮模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2734825/

相关文章:

wpf - 在 WPF 键处理程序中,我可以通过编程方式更改/覆盖按下的键吗?

c# - 重载的 RadTextBox 控件中的服务器端自定义验证器不调用其客户端验证函数

android - 如何为布局设置不同的主题

html - 悬停时不显示标签

ios - 如何在 iOS 中添加相对于其他 UI 元素的 UILabel

wpf - WPF 中的样式和绑定(bind)

wpf - MVVM 将 viewmodel 属性子项绑定(bind)到 viewmodel 属性

C# WPF 内容切换

wpf - 未定义的 CLR 命名空间

c# - 覆盖标签 OnPaint?