我正在尝试构建我的UWP应用程序,但在尝试在资源字典中使用DataTemplate和x:Bind时,遇到了设计器异常问题。
我创建了一个名为“ItemTemplates.xaml”的资源字典,并创建了相应的代码后台(以确保x:Bind初始化)。该文件仅包含一个模板:
<DataTemplate x:Key="HomeViewCategoryListItemTemplate" x:DataType="models:Category">
<Button Background="#88333333" Height="110" VerticalContentAlignment="Top" Padding="10" HorizontalAlignment="Stretch">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock FontWeight="Light" HorizontalAlignment="Center" Text="{x:Bind Name}" FontSize="{ThemeResource TextStyleExtraLargeFontSize}" />
<TextBlock Foreground="{ThemeResource ToolTipForegroundThemeBrush}" HorizontalAlignment="Center" Margin="0,10,0,0" Text="{x:Bind Description}" Grid.Row="1" TextAlignment="Center" TextWrapping="Wrap" />
</Grid>
</Button>
</DataTemplate>
然后我像这样将资源字典添加到App.xaml中:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ms-appx:///Resources/Core.xaml" />
<resources:ItemTemplates />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
现在该项目无法使用,因为设计师会抛出奇怪的异常,但是当我清理并重新构建项目,并导航到HomeView.xaml页面时,设计师只显示默认的“ToString()”项目(基本上列表视图只包含三个文本“Models.Categories”),我的ListView的ItemTemplate属性被下划线标记并显示以下错误:
The resource "HomeViewCategoryListItemTemplate" could not be resolved.
当我回到App.xaml时,我看到另一个下划线(在
<resources:ItemTemplates />
一行)下面有一行字,内容是:The property 'DataType' was not found in type 'DataTemplate'.
两个错误都是无意义的,因为当我实际运行应用程序时,没有任何问题,一切都完美地工作。到目前为止,我找到的唯一解决方法是在经典方式和“编译”方式中分别两次包括ResourceDictionary:
<ResourceDictionary Source="ItemTemplates.xaml" />
<resoures:ItemTemplates />
这个解决方案可以在设计时和运行时都正常工作,但我认为它非常混乱,一定有更好、更安全的方法,或者我错过了一些微不足道的东西。
我正在使用Visual Studio 2015 Update 1,并安装了最新的UWP SDK。该项目的目标是构建10240版本。
编辑: 另一个异常,设计师经常抛出并完全崩溃:
Unable to cast object of type 'System.String' to type 'Models.Data.Categories.Category'.
根据StackTrace输出,这个问题发生在ItemTemplates.xaml.cs代码中——具体地说是在生成的方法“ProcessBindings”中。项目仍然可以编译和正常运行,但设计器甚至不会尝试显示输出。