我在. Net Maui中声明了全局样式,并尝试从其中一个页面访问它,但它抛出了异常
异常错误:位置10:37。类型转换器失败:调用的目标引发了异常。位置8:34。找不到主键的StaticResource。**
应用程序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:local="clr-namespace:MyApp"
x:Class="MyApp.App">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/Styles/Colors.xaml" />
<ResourceDictionary Source="Resources/Styles/Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
<Style x:Key="redLabelStyle"
TargetType="Label">
<Setter Property="TextColor"
Value="Red"/>
<Setter Property="FontSize"
Value="Small"/>
<Setter Property="FontAttributes"
Value="Bold"/>
</Style>
<Style TargetType="Label">
<Setter Property="TextColor"
Value="Green"/>
<Setter Property="FontSize"
Value="Small"/>
<Setter Property="FontAttributes"
Value="Bold"/>
</Style>
</Application.Resources>
主页. xaml代码
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
NavigationPage.HasNavigationBar="False"
x:Class="MyApp.MainPage">
<VerticalStackLayout HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand">
<Label Style="{StaticResource redLabelStyle}"
Text="Global Style Red Label"/>
<Label Text="GLobal Style Green Label"/>
<Label Text="GLobal Style Green Label"/>
</VerticalStackLayout>
</ContentPage>
- 注意:**这是. Net Maui创建的默认应用程序。
2条答案
按热度按时间6vl6ewon1#
我想这是个错误的地方
试试这个:
同时为第二个样式命名。
<Style TargetType="Label">
在x:Key=""
中命名喜欢
pnwntuvh2#
还可以将全局样式添加到MergedDictionaries中引用的
Styles.xaml
文件请注意文件的位置
您可以直接将样式复制到那里,这样您就可以将所有的全局样式保存在一个中心位置,这有助于保持App.xaml的整洁。