![](/img/trans.png)
[英]Mysterious name resolution differences between legacy and SDK-style C# projects
[英]MAUI: Unable to share ResourceDictionaries between two SDK-style projects
我有两个 SDK 风格的 MAUI 项目,比如说 Project1 和 Project2。 Project2 具有以下结构:
Project2.sln
|
- Resources
|
- Colors.xaml
Colors.xaml 具有以下代码:
<?xml version="1.0" encoding="UTF-8" ?>
<?xaml-comp compile="true" ?>
<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Project2.Resources.Colors">
<Color x:Key="TestColor">#512BD4</Color>
</ResourceDictionary>
目标是在 Project1 中使用TestColor
,可能稍后在 Project3、Project4 等中使用。 只要标准的类似 WPF 的 XAML 表示法在 MAUI 中不起作用,我们就必须包含此文件,如下所示:
项目 1/App.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:resources="clr-namespace:Project2.Resources;assembly=Project2"
x:Class="Project1.App">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<resources:Colors />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
这个至少可以编译没有错误,但这不起作用。 当我尝试在某些视图中使用新的静态资源时,如下所示:
项目 1/MainWindow.xaml:
<Grid BackgroundColor="{StaticResource TestColor}" />
它会引发运行时错误Microsoft.Maui.Controls.Xaml.XamlParseException: 'Position XX:XX. StaticResource not found for key TestColor'
Microsoft.Maui.Controls.Xaml.XamlParseException: 'Position XX:XX. StaticResource not found for key TestColor'
并且 IntelliSense 对 TestColor 没有任何线索。 问题是:我需要如何使用 MAUI 在其他项目中正确链接我的外部 ResourceDictionary?
解决方法:在应用启动期间,手动将 dll 资源字典中的所有条目复制到Application.Current.Resources
中。
在共享App.xaml.cs
中:
public App()
{
InitializeComponent();
// TODO: Code to get dll's resourcedictionary.
ResourceDictionary rd1 = ...; // Project2.Resources?
// Copy all entries into app's Resources.
foreach (KeyValuePair<string, object> entry in rd1)
{
Application.Current.Resources[entry.Key] = entry.Value;
}
MainPage = new AppShell(); // Or whatever you have here.
}
TODO:获取 dll 资源字典的代码。
我没有在毛伊岛使用过 dll,因此不确定此步骤所需的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.