Important
有关有助于理解如何通过 C++/WinRT 使用和创作运行时类的基本概念和术语,请参阅 通过 C++/WinRT 使用 API 和 通过 C++/WinRT 创作 API。
实现 可重写 方法,例如 MeasureOverride 和 OnApplyTemplate
XAML 中有一些扩展点,应用程序可以插入其中,例如:
从 Control 运行时类派生自定义控件,该类本身进一步派生自基运行时类。 还有一些 Control、FrameworkElement 和 UIElement 的 overridable 方法可在派生类中重写。 下面是一个代码示例,演示如何实现这一点。
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();
}
};