XAML WinUI 3中的抗拼写导航视图项目标记

uqxowvwt  于 2022-12-16  发布在  其他
关注(0)|答案(1)|浏览(168)

我正在尝试将类型参数传递给XAML中NavigationViewItem元素的Tag属性:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:page="using:MyApp.Pages"
>
    <NavigationView>
        <NavigationView.MenuItems>
            <NavigationViewItem Content="Test page" Tag="{x:Type page:TestPage}" Icon="Library" />
        </NavigationView.MenuItems>
        <Frame x:Name="contentFrame" />
    </NavigationView>
</Page>

出现错误:“类型x:找不到类型。"。
当我为此创建自定义扩展时:

using Microsoft.UI.Xaml.Markup;
using System;

namespace MyApp.Xaml
{
    [MarkupExtensionReturnType(ReturnType = typeof(Type))]
    public sealed class TypeExtension : MarkupExtension
    {
        public Type Type { get; set; }

        public TypeExtension(Type type)
        {
            Type = type;
        }

        protected override object ProvideValue() => Type;
    }
}

并像这样使用它:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:t="using:MyApp.Xaml"
    xmlns:page="using:MyApp.Pages"
>

    <NavigationView >
        <NavigationView.MenuItems>
            <NavigationViewItem Content="Test page" Tag="{t:Type page:TestPage}" Icon="Library" />
        </NavigationView.MenuItems>
        <Frame x:Name="contentFrame" />
    </NavigationView>
</Page>

它仍然不工作,出现错误:

Error   WMC0100 XAML TypeExtension type cannot be constructed. In order to be constructed in XAML, a type cannot be abstract, interface, nested, generic or a struct, and must have a public default constructor.

有人知道如何解决将Type传递给Tag属性的问题,或者其他防止类名拼写错误的解决方案吗?
为完整起见,我的选择更改处理程序:

private void MainNavigationView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
        {
            if (args.SelectedItem is NavigationViewItem item && item.Tag is Type pageType)
            {
                contentFrame.Navigate(pageType);
            }
        }
8oomwypt

8oomwypt1#

尝试像这样传递Type

[MarkupExtensionReturnType(ReturnType = typeof(Type))]
public sealed class TypeExtension : MarkupExtension
{
    public Type? Type { get; set; }

    protected override Type? ProvideValue()
    {
        return Type;
    }
}
<NavigationViewItem Content="Home" Tag="{l:Type Type=pages:HomePage}"/>

但是当你用MarkupExtensions返回Type时,WinUI 3中有一个正在进行的issue,所以你必须等到他们修复它。

相关问题