无法覆盖 OnApplyTemplate

Unable to override OnApplyTemplate

我正在尝试覆盖 NavigationView 行为:


    public partial class CustomizableNavigationView : NavigationView
    {
        public CustomizableNavigationView()
        {
            // This gets called
        }

        protected override void OnApplyTemplate()
        {
            // This doesn't

        }
    }

它适用于 UWP,但不适用于 Android。在 Android 上,它没有调用 OnApplyTemplate 并且屏幕保持空白,没有内容。问题:

  1. 为什么 OnApplyTemplate 没有在 Android 上被调用?我在这里看到:https://platform.uno/docs/articles/implemented/windows-ui-xaml-frameworkelement.html 它说 OnApplyTemplate() 是在所有平台上

  2. 当 运行 调试器时,VS 的输出面板中没有错误或任何显示。在这种情况下应该有吗?我需要启用某些功能来记录错误吗?

  3. 我注意到,如果我不使用 partial,它会提示我需要 partial。这仅在 Android 上是必需的,这是为什么呢?更深入的解释将有助于理解事物的工作原理。

  4. 一旦弄清楚为什么不调用 OnApplyTemplate,我想这样做:

 base.OnApplyTemplate();
            var settingsItem = (NavigationViewItem)GetTemplateChild("SettingsNavPaneItem");
            settingsItem.Content = "Custom text";

我的预感是这在 Android 上不起作用。我对么? :)

在当前版本(1.45 及更低版本)中,样式应用的行为与 UWP 不同。我们正在跟踪这个 in this issue.

问题的要点是 Uno 使用当前类型而不是 DefaultStyleKey 解析样式,并且找不到 CustomizableNavigationView 的隐式样式。

解决此问题的方法是创建命名样式 from the default NavigationView style,或创建使用 CustomizableNavigationView 作为 TargetType 而不是 NavigationView 的隐式样式。

Jerome 的回答解释了为什么 OnApplyTemplate() 没有被调用,以解决您的其他问题:

  1. 您可以为 Uno 配置日志过滤器,这通常是定义 in App.xaml.cs。默认情况下应记录警告。

  2. partial 是必需的,因为 Uno 在幕后执行一些代码生成以创建 Xamarin 运行时使用的管道方法。具体是因为控件最终是继承自ViewGroup on Android, it's a native object, and requires special constructors that are used only by Xamarin's interop layer. There's some documentation in progress on this.

  3. 试试看。 :) 支持GetTemplateChild(),并且支持这样设置ContentControl.Content,所以我希望它能工作。