使用 C++/WinRT 调用和替代基类型

重要

有关支持你了解如何利用 C++/WinRT 来使用和创作运行时类的基本概述和术语,请参阅通过 C++/WinRT 使用 API通过 C++/WinRT 创作 API

实现 MeasureOverride 和 OnApplyTemplate 等可重写的方法

应用程序可以插入 XAML 中的一些扩展点,例如:

可以从 Control 运行时类派生自定义控件,而该运行时类本身派生自基本运行时类。 以下是一些可在派生类中替代的 Control、FrameworkElementUIElementoverridable 方法。 下面的代码示例演示了如何执行该操作。

struct BgLabelControl : BgLabelControlT<BgLabelControl>
{
...
    // Control overrides.
    void OnPointerPressed(Windows::UI::Xaml::Input::PointerRoutedEventArgs const& /* e */) const { ... };

    // FrameworkElement overrides.
    Windows::Foundation::Size MeasureOverride(Windows::Foundation::Size const& /* availableSize */) const { ... };
    void OnApplyTemplate() const { ... };

    // UIElement overrides.
    Windows::UI::Xaml::Automation::Peers::AutomationPeer OnCreateAutomationPeer() const { ... };
...
};

可重写方法在不同语言投影中呈现出不同形式。 例如,在 C# 中可重写方法通常呈现为受保护的虚拟方法。 在 C++/WinRT 中,它们既不是虚拟的也不是受保护的,但你仍可以覆盖它们并提供你自己的实现,如上所示。

如果要在 C++/WinRT 中重写这些可重写方法之一,则 runtimeclass IDL 不得声明该方法。 有关所显示 base_type 语法的详细信息,请参阅本主题中的下一部分(调用基类型)。

IDL

namespace Example
{
    runtimeclass CustomVSM : Windows.UI.Xaml.VisualStateManager
    {
        CustomVSM();
        // note that we don't declare GoToStateCore here
    }
}

C++/WinRT

namespace winrt::Example::implementation
{
    struct CustomVSM : CustomVSMT<CustomVSM>
    {
        CustomVSM() {}

        bool GoToStateCore(winrt::Windows::UI::Xaml::Controls::Control const& control, winrt::Windows::UI::Xaml::FrameworkElement const& templateRoot, winrt::hstring const& stateName, winrt::Windows::UI::Xaml::VisualStateGroup const& group, winrt::Windows::UI::Xaml::VisualState const& state, bool useTransitions) {
            return base_type::GoToStateCore(control, templateRoot, stateName, group, state, useTransitions);
        }
    };
}

调用基类型

可以使用类型别名 base_type 访问基类型并对其调用方法。 我们在上一部分中看到了一个这样的示例;但你可以使用 base_type 访问任何基类成员(而不仅仅是替代的方法)。 下面是一个示例:

struct MyDerivedRuntimeClass : MyDerivedRuntimeClassT<MyDerivedRuntimeClass>
{
    ...

    void Foo()
    {
        // Call my base type's Bar method.
        base_type::Bar();
    }
};

重要的 API