[英]Equivalent of x:Type in UWP
I have this class:我有这门课:
public class EditorKey
{
public Type TargetType { get; set; }
public DataTemplate Template { get; set; }
}
Now, I want to create an instance of this class in XAML.现在,我想在 XAML 中创建此类的一个实例。 Since in UWP we don't have the x:Type markup extension, I'm specifying the type directly as a string, with the correct prefix with
TargetType="model:Customer"
由于在 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>
Running this, I get a runtime exception:运行这个,我得到一个运行时异常:
Failed to create a 'App8.EditorKey' from the text 'model:Customer'.无法从文本“model:Customer”创建“App8.EditorKey”。
How can I map the string to the actual Type?如何将字符串映射到实际类型?
The usual way of doing it in UWP is to simply supply the reference as a string:在 UWP 中执行此操作的通常方法是简单地将引用作为字符串提供:
<model:EditorKey TargetType="model:Customer" />
If this doesn't work, try specifying the full namespace, rather than defining an xmlns
.如果这不起作用,请尝试指定完整的命名空间,而不是定义
xmlns
。
Example:例子:
<model:EditorKey TargetType="App8.Customer" />
Note: As of time of writing, there's an issue where the above will crash in Release mode.注意:截至撰写本文时,存在上述问题在 Release 模式下会崩溃。 As a workaround, you can create a Markup extension:
作为一种解决方法,您可以创建一个标记扩展:
[MarkupExtensionReturnType(ReturnType = typeof(Type))]
public sealed class TypeExtension : MarkupExtension
{
public Type Type { get; set; }
/// <inheritdoc/>
protected override object ProvideValue() => Type;
}
And use it like so:并像这样使用它:
<model:EditorKey TargetType="{local:Type Type=model:Customer"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.