使用MergedDictionaries(UWP)

时间:2015-10-23 05:35:17

标签: xaml custom-controls windows-10 uwp

考虑我创建包含一组自定义控件的库MyCustomControlsProject的情况。我没有将所有这些控件的XAML代码放在一个非常大的generic.xaml中,而是希望将每个控件分离到自己的XAML文件中,然后从generic.xaml中引用该文件

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="<url_syntax_file_1>" />
    <ResourceDictionary Source="<url_syntax_file_2>" />
</ResourceDictionary.MergedDictionaries>

解决方案资源管理器(以及文件系统)中的文件夹结构如下所示:

  • MyCustomControlsProject(项目/文件夹)
    • 主题(文件夹)
      • Generic.xaml(file)
      • ControlTemplates(文件夹)
        • MyControl1.xaml(档案)
        • MyControl2.xaml(文件)

过去,我使用以下语法在Silverlight和Silverlight for Win Phone中执行此操作:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="/MyCustomControlsProject;Component/Themes/ControlTemplates/MyControl1.xaml"/>
    <ResourceDictionary Source="/MyCustomControlsProject;Component/Themes/ControlTemplates/MyControl2.xaml"/>
</ResourceDictionary.MergedDictionaries>

对于使用此语法的Windows Phone 8.1:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="ms-appx:///Themes/ControlTemplates/MyControl1.xaml" />
    <ResourceDictionary Source="ms-appx:///Themes/ControlTemplates/MyControl2.xaml" />
</ResourceDictionary.MergedDictionaries>

这些语法都不适用于Win 10(UWP)。尝试使用这些会导致运行时异常:

An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in MyApplication.exe but was not handled in user code
WinRT information: Failed to assign to property 'Windows.UI.Xaml.ResourceDictionary.Source' because the type 'Windows.Foundation.String' cannot be assigned to the type 'Windows.Foundation.Uri'.

我也试过这种语法导致了同样的异常:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="ControlTemplates/MyControl1.xaml" />
    <ResourceDictionary Source="ControlTemplates/MyControl2.xaml" />
</ResourceDictionary.MergedDictionaries>

有趣的是,似乎app.xaml使用上面的语法没有问题。

有人知道generic.xaml中source节点的ResourceDictionary属性中url字符串的正确语法吗?或者这是UWP没有赶上的东西吗?

2 个答案:

答案 0 :(得分:5)

正确的语法是:

<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="ms-appx:///MyCustomControlsProject/Themes/ControlTemplates/MyControl1.xaml" />
    <ResourceDictionary Source="ms-appx:///MyCustomControlsProject/Themes/ControlTemplates/MyControl2.xaml" />
</ResourceDictionary.MergedDictionaries>

答案 1 :(得分:0)

您需要在上次尝试时添加Themes文件夹:

<ResourceDictionary>  
  <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Themes/ControlTemplates/MyControl1.xaml" />
        <ResourceDictionary Source="Themes/ControlTemplates/MyControl2.xaml" />
    </ResourceDictionary.MergedDictionaries>
   </ResourceDictionary>