Share via


C++/WinRT を使用した基本型の呼び出しとオーバーライド

重要

C++/WinRT でランタイム クラスを使用および作成する方法についての理解をサポートするために重要な概念と用語については、「C++/WinRT での API の使用」と「C++/WinRT での API の作成」を参照してください。

MeasureOverrideOnApplyTemplate などの "オーバーライド可能な" 関数の実装

XAML には、アプリケーションからプラグインできる拡張ポイントがあります。次に例を示します。

カスタム コントロールは Control ランタイム クラスから派生し、それ自体も基本ランタイム クラスから派生します。 また、派生クラスでオーバーライドできる ControlFrameworkElement、および UIElementoverridable メソッドがあります。 この方法を示すコード例を次に示します。

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