在写WPF程序时,出现了以下错误,看错误名,应该是xaml的解释器未找到StaticResourceExtension的资源,后来参考文章:https://muzizongheng.blog.csdn.net/article/details/85127317
我发现StaticResource用于xaml加载时使用ResourceDictionary中x:Key定义的资源,必须先定义再使用,不然会抛出异常。原来的xaml代码如下:
<Window x:Class="WpfStringResources.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfStringResources"
xmlns:system="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="357" Width="500">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="name1" Text="{StaticResource ResourceKey=name1}" Margin="90,70"/>
<TextBlock Text="{StaticResource ResourceKey=name2}" Margin="90,70" Grid.Column="1"/>
<TextBlock Text="{DynamicResource ResourceKey=name3}" Margin="90,70" Grid.Row="1"/>
<TextBlock Text="{DynamicResource ResourceKey=name4}" Margin="90,70" Grid.Row="1" Grid.Column="1"/>
</Grid>
<Window.Resources>
<system:String x:Key="name1">床前明月光,</system:String>
<system:String x:Key="name2">疑是地上霜。</system:String>
<system:String x:Key="name3">举头望明月,</system:String>
<system:String x:Key="name4">低头思故乡。</system:String>
</Window.Resources>
</Window>
将定义的window.Resources放在<Grid>之前就能成功运行了!