我正在创建一个模仿 AppBarButton
的自定义控件(但具有自定义功能,因此我们无法从 AppBarButton
派生)。
我的问题是 AppBarButton
的 Icon
属性。该属性本身采用 IconElement
,但如果您正在创建 AppBarButton
并指定内联 Icon
,它将默认为 Symbol
枚举并为您创建一个 SymbolIcon
。
我的问题是:我将如何复制它?我似乎找不到有关如何执行此操作的任何信息。
谢谢!
最佳答案
IconElement是这些类的父类:
所以给AppBarButton
的Icon
属性赋值一个SymbolIcon
是没有问题的。并且在 UWP XAML 系统中,内置了对 SymbolIcon
的类型转换器支持。对于复制,您应该能够定义 DependencyProperty哪种类型是 IconElement
,然后像在 AppBarButton
中一样使用它。
举个简单的例子,我创建了一个名为“CustomAppBarButton”的模板化控件,其依赖属性名为“Icon”。
CustomAppBarButton.cs:
public sealed class CustomAppBarButton : Control
{
public CustomAppBarButton()
{
this.DefaultStyleKey = typeof(CustomAppBarButton);
}
public IconElement Icon
{
get { return (IconElement)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
// Using a DependencyProperty as the backing store for Icon. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconProperty =
DependencyProperty.Register("Icon", typeof(IconElement), typeof(CustomAppBarButton), new PropertyMetadata(null));
}
Generic.xaml:
<Style TargetType="local:CustomAppBarButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomAppBarButton">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ContentPresenter x:Name="Content"
HorizontalAlignment="Stretch"
Content="{TemplateBinding Icon}"
Foreground="{TemplateBinding Foreground}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然后你就可以像下面这样使用了。
<local:CustomAppBarButton Icon="Like" Foreground="Red" />
关于C# DependencyProperty - 对复杂类型使用默认属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43219532/