【发布时间】:2020-01-10 09:19:58
【问题描述】:
我需要一个具有自定义样式的按钮,并且我想在上面放一张图片。
所以我用 ControlTemplate 制作了 CustomButton 样式,其中包含 TextBlock 的 StackPanel 用于文本和 Rectangle 用于图像,我想使用 Icons.xaml 中的 DrawingImage,它是 SVG 转换为 XAML。
我也做了CustomButton类,它是从普通的Button类派生的,并且有DrawingImageProperty,它是依赖属性。
在我看来,我想用 DrawingImage 属性创建这个按钮,然后以我的风格绑定到这个属性,如下所示:
<controls:CustomButton DrawingImage="{StaticResource Add}" Content="Add" Style="{StaticResource CustomButton}" />
但不幸的是,按钮图像丢失了。我不确定绑定到样式中的依赖属性,我也不确定类型,因为 DrawingBrush 的绘图属性是绘图类型,但是在我的 Icons.xaml 资源中我有 DrawingImage,不能这样吗也有问题?
CustomButton.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:Torch.Controls">
<Style x:Key="CustomButton" TargetType="{x:Type controls:CustomButton}">
<Setter Property="Foreground" Value="{StaticResource IconicWhiteBrush}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:CustomButton}">
<Border
Name="Border"
Background="{StaticResource IconicBlueLittleDarkBrush}"
BorderBrush="{StaticResource IconicBlackBrush}"
BorderThickness="1">
<StackPanel Orientation="Horizontal">
<Rectangle Width="20" Height="20">
<Rectangle.Fill>
<DrawingBrush Drawing="{TemplateBinding DrawingImage}" />
</Rectangle.Fill>
</Rectangle>
<TextBlock
Margin="0,0,5,0"
VerticalAlignment="Center"
Text="{TemplateBinding Content}" />
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
自定义按钮.cs
public class CustomButton : Button
{
public static readonly DependencyProperty DrawingImageProperty =
DependencyProperty.Register("DrawingImage", typeof(DrawingImage), typeof(CustomButton),
new FrameworkPropertyMetadata(OnDrawingImageChanged));
public DrawingImage DrawingImage
{
get => (DrawingImage)GetValue(DrawingImageProperty);
set => SetValue(DrawingImageProperty, value);
}
private static void OnDrawingImageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((CustomButton)d).DrawingImage = (DrawingImage)e.NewValue;
}
}
图标.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DrawingImage x:Key="Add">
<DrawingImage.Drawing>
<DrawingGroup ClipGeometry="M0,0 V24 H24 V0 H0 Z">
<GeometryDrawing Brush="#FF00ACC1" Geometry="F1 M24,24z M0,0z M19,13L13,13 13,19 11,19 11,13 5,13 5,11 11,11 11,5 13,5 13,11 19,11 19,13z" />
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</ResourceDictionary>
谢谢。
【问题讨论】: