XAML 在另一个资源字典文件中使用一个dotnet Maui资源字典文件中的键

p5fdfcr1  于 2023-08-01  发布在  其他
关注(0)|答案(1)|浏览(157)

我有两个资源字典文件,Colors.xaml和Styles.xaml
我从App.xaml使用它们,如下所示

<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Colors.xaml" />
                <ResourceDictionary Source="Resources/Styles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

字符串
我希望Styles.xaml中的节点能够使用Colors
例如Colors.xaml中的

<Color x:Key="MySpecialColor">#0000FF</Color>
<Setter Property="TextColor" Value="{StaticResource MySpecialColor}" />

该应用程序编译,我甚至可以控制+点击VS2022从MySpecialColor的使用Styles.xaml和它去正确的地方在Colors.xaml,但在运行时,我得到这个错误

[mono-rt]  ---> Microsoft.Maui.Controls.Xaml.XamlParseException: Position 25:58. StaticResource not found for key MySpecialColor


This answer来自一个相对类似的关于WPF而不是Maui的问题,建议使用DynamicResource而不是静态资源。这对毛伊岛不起作用,我得到了同样的错误。另外,即使它做了,我想静态类型,如果我可以。

voase2hg

voase2hg1#

首先,你检查默认的maui项目模板了吗?/Resources/Styles文件夹下有两个资源字典:颜色.xaml和样式. xaml。

<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
                <ResourceDictionary Source="Resources/Styles/Styles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

字符串
Colors.xaml中的密钥在Styles.xaml中使用。我还尝试在Colors.xaml中添加自定义颜色:

<Color x:Key="MyColor">#0000FF</Color>


并将其用于Button的样式:

<Style TargetType="Button">
        <Setter Property="TextColor" Value="{StaticResource MyColor}" />


按钮的文本颜色将被更改。

相关问题