【发布时间】:2021-01-08 04:19:56
【问题描述】:
我正在尝试使用 cpp/winrt 为 ListView 动态创建 DataTemplate:
auto template_src = R"(
<DataTemplate
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyNamespace"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:DataType="local:MyListItem"
>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Bind MyProperty}" HorizontalAlignment="Left"/>
</StackPanel>
</DataTemplate>
)";
auto tmpl = winrt::Windows::UI::Xaml::Markup::XamlReader::Load(winrt::to_hstring(template_src)).as<winrt::Windows::UI::Xaml::DataTemplate>();
Load 调用抛出异常:
在类型“DataTemplate”中找不到属性“DataType”。 [行:8 位置:17]
MyListItem 类型是自定义的 winrt 类型。使用 x:Bind 时需要 DataType 属性。
如果我删除该属性并按如下方式替换绑定,它不会崩溃但也不会呈现:
auto template_src = R"(
<DataTemplate
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyNamespace"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding MyProperty}" HorizontalAlignment="Left"/>
</StackPanel>
</DataTemplate>
)";
auto tmpl = winrt::Windows::UI::Xaml::Markup::XamlReader::Load(winrt::to_hstring(template_src)).as<winrt::Windows::UI::Xaml::DataTemplate>();
如果我在 Xaml 中声明模板:
<Page.Resources>
<DataTemplate x:Key="ListTemplate" x:DataType="local:MyListItem">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Bind MyProperty, Mode=OneWay}" HorizontalAlignment="Left"/>
</StackPanel>
</DataTemplate>
</Page.Resources>
并加载它
Resources().Lookup(winrt::box_value(L"ListTemplate")).as<winrt::Windows::UI::Xaml::DataTemplate>());
列表正确呈现。
【问题讨论】:
标签: uwp winrt-xaml uwp-xaml c++-winrt