我想创建一个简单的按钮模板,其中包含图像和文本。但是我想保持系统按钮的外观。
如何逐步创建它?
附注:我已经在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/