我正在尝试将类型参数传递给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);
}
}
1条答案
按热度按时间8oomwypt1#
尝试像这样传递
Type
:但是当你用
MarkupExtensions
返回Type
时,WinUI 3中有一个正在进行的issue,所以你必须等到他们修复它。