C# DependencyProperty - 对复杂类型使用默认属性

标签 c# uwp custom-controls

我正在创建一个模仿 AppBarButton 的自定义控件(但具有自定义功能,因此我们无法从 AppBarButton 派生)。

我的问题是 AppBarButtonIcon 属性。该属性本身采用 IconElement,但如果您正在创建 AppBarButton 并指定内联 Icon,它将默认为 Symbol 枚举并为您创建一个 SymbolIcon

我的问题是:我将如何复制它?我似乎找不到有关如何执行此操作的任何信息。

谢谢!

最佳答案

IconElement是这些类的父类:

所以给AppBarButtonIcon属性赋值一个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/

相关文章:

c# - 填充 UI 时显示请稍候动画

c# - Azure Batch 的错误,从任务项初始化作业对象

c# - 使用UWP以AMR-NB编码捕获音频?

visual-studio-2015 - 在 VS2015 中部署 UWP App 项目

css - 如何在 JavaFx 的组合/选择框中为特定元素添加自定义 css 样式?

c# - ASP.NET Ajax Accordion header 事件

c# - 我可以将 Form 设为单例吗?

c# - x :Bind Converter and FallbackValue not collaborating (UWP 10)

ios - iOS 中的抗锯齿自定义栏按钮图像

algorithm - 大用户事件序列到树