使用 C++/WinRT 呼叫及覆寫你的基底類型

這很重要

如需有助於了解如何使用及撰寫 C++/WinRT 執行階段類別的基本概念與術語,請參閱《Consume APIs with C++/WinRT》和《Author APIs with C++/WinRT》。

實作可覆寫的方法,例如 MeasureOverrideOnApplyTemplate

XAML 中有一些擴充點可以插入,例如:

你可以從 Control 執行時類別衍生出自訂控制項,而 Control 本身又進一步衍生自基礎執行時類別。 此外,overridable 你也可以在衍生類別中覆寫 ControlFrameworkElementUIElement 所提供的方法。 以下是示範如何執行此動作的程式代碼範例。

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

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

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

可覆寫的方法在不同的語言投影中會以不同的方式呈現。 例如在 C# 中,可覆寫的方法通常會以受保護的虛擬方法形式出現。 在 C++/WinRT 中,它們既不是虛擬也不是受保護的,但您仍然可以覆寫它們並提供您自己的實作,如上所示。

如果你在 C++/WinRT 中覆寫這些可覆寫的方法,那麼你的 runtimeclass IDL 就不能宣告該方法。 如需顯示的 base_type 語法詳細資訊,請參閱本主題的下一節(呼叫基底類型)。

IDL

namespace Example
{
    runtimeclass CustomVSM : Microsoft.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::Microsoft::UI::Xaml::Controls::Control const& control, winrt::Microsoft::UI::Xaml::FrameworkElement const& templateRoot, winrt::hstring const& stateName, winrt::Microsoft::UI::Xaml::VisualStateGroup const& group, winrt::Microsoft::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