MAUI中如何在Windows平台代码中引用共享样式文件的颜色
在.NET MAUI Windows平台引用共享Colors.xaml资源的方案
一、在Windows平台App.xaml中引用共享颜色资源
Windows平台的App.xaml默认不会自动包含共享项目中的资源字典,需要手动合并共享的Colors.xaml:
- 打开
./Platforms/Windows/App.xaml,在ResourceDictionary.MergedDictionaries中添加对共享资源的引用:
<Application x:Class="YourApp.WinUI.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:YourApp.WinUI"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" /> <!-- 引用根目录下的共享Colors.xaml --> <ResourceDictionary Source="../../Styles/Colors.xaml" /> </ResourceDictionary.MergedDictionaries> <!-- 此处保留Windows平台专属资源定义 --> </ResourceDictionary> </Application.Resources> </Application>
- 验证路径正确性:
../../Styles/Colors.xaml是从Platforms/Windows/App.xaml向上回溯两级到项目根目录,再定位到Styles文件夹下的文件,若项目结构不同,需调整相对路径。 - 确保共享的
Colors.xaml的Build Action设置为Embedded Resource(右键文件→属性→Build Action)。
完成后即可在Windows平台XAML中直接使用{StaticResource IIT_Purple},无需重复定义颜色。
二、在Windows平台App.xaml.cs中获取共享颜色
无需重复定义颜色值,可直接从已合并的资源字典中获取:
方法1:从应用全局资源中读取
using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Media; // 在App.xaml.cs的合适位置获取颜色 var sharedColor = (Color)Application.Current.Resources["IIT_Purple"]; // 转换为Windows.UI.Color类型(若需要) var windowsColor = Windows.UI.Color.FromArgb(sharedColor.A, sharedColor.R, sharedColor.G, sharedColor.B);
方法2:直接加载共享资源字典
如果未在App.xaml中合并资源,也可手动加载Colors.xaml:
using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Media; var resourceDict = new ResourceDictionary(); // 使用相对路径加载共享资源 resourceDict.Source = new Uri("../../Styles/Colors.xaml", UriKind.Relative); var sharedColor = (Color)resourceDict["IIT_Purple"]; var windowsColor = sharedColor.ToWindowsColor();
内容的提问来源于stack exchange,提问作者Danny Beckett
相关产品推荐
相关产品推荐

