相当于 x:在 UWP 中键入



我有这个类:

public class EditorKey
{
    public Type TargetType { get; set; }
    public DataTemplate Template { get; set; }
}

现在,我想在 XAML 中创建此类的实例。由于在 UWP 中我们没有 x:Type 标记扩展名,因此我直接将类型指定为字符串,并使用正确的前缀和 TargetType="model:Customer"

<Page
    x:Class="App8.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:model="using:App8"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <ContentControl>
        <model:EditorKey TargetType="model:Customer" />
    </ContentControl>
</Page>

运行这个,我得到一个运行时异常:

无法从文本"模型:客户"创建"App8.EditorKey"。

如何将字符串映射到实际类型?

在 UWP 中执行此操作的常用方法是简单地将引用作为字符串提供:

<model:EditorKey TargetType="model:Customer" />

如果这不起作用,请尝试指定完整的命名空间,而不是定义xmlns

例:

<model:EditorKey TargetType="App8.Customer" />
<小时 />

注意:截至撰写本文时,存在一个问题,即上述内容将在发布模式下崩溃。作为解决方法,您可以创建标记扩展:

[MarkupExtensionReturnType(ReturnType = typeof(Type))]
public sealed class TypeExtension : MarkupExtension
{
    public Type Type { get; set; }
    /// <inheritdoc/>
    protected override object ProvideValue() => Type;
}

并像这样使用它:

<model:EditorKey TargetType="{local:Type Type='App8.Customer'"/>

最新更新