用于特殊目的的动态资源
用于引用Resources字典中的项的StaticResource的替代方法是DynamicResource,如果您在上面的示例中仅使用DynamicResource替换StaticResource,则程序似乎运行相同。但是,这两个标记扩展非常不同。在解析XAML并构建页面时,StaticResource仅访问字典中的项目一次。但DynamicResource维护字典键和该字典项的属性集之间的链接。如果键引用的资源字典中的项发生更改,DynamicResource将检测到该更改并将新值设置为该属性。
持怀疑态度?我们来试试吧。 DynamicVsStatic项目有一个XAML文件,它定义了一个类型为string的资源项,其键为currentDateTime,即使字典中的项是字符串“Not actual a DateTime”!
此字典项在XAML文件中被引用四次,但其中一个引用被计算出来。在前两个示例中,Label的Text属性是使用StaticResource和DynamicResource设置的。在后两个示例中,Span对象的Text属性设置类似,但在Span对象上使用DynamicResource会出现在注释中:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DynamicVsStatic.DynamicVsStaticPage"
Padding="5, 0">
<ContentPage.Resources>
<ResourceDictionary>
<x:String x:Key="currentDateTime">Not actually a DateTime</x:String>
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout>
<Label Text="StaticResource on Label.Text:"
VerticalOptions="EndAndExpand"
FontSize="Medium" />
<Label Text="{StaticResource currentDateTime}"
VerticalOptions="StartAndExpand"
HorizontalTextAlignment="Center"
FontSize="Medium" />
<Label Text="DynamicResource on Label.Text:"
VerticalOptions="EndAndExpand"
FontSize="Medium" />
<Label Text="{DynamicResource currentDateTime}"
VerticalOptions="StartAndExpand"
HorizontalTextAlignment="Center"
FontSize="Medium" />
<Label Text="StaticResource on Span.Text:"
VerticalOptions="EndAndExpand"
FontSize="Medium" />
<Label VerticalOptions="StartAndExpand"
HorizontalTextAlignment="Center“
FontSize="Medium">
<Label.FormattedText>
<FormattedString>
<Span Text="{StaticResource currentDateTime}" />
</FormattedString>
</Label.FormattedText>
</Label>
<!-- This raises a run-time exception! -->
<!--<Label Text="DynamicResource on Span.Text:"
VerticalOptions="EndAndExpand"
FontSize="Medium" />
<Label VerticalOptions="StartAndExpand"
HorizontalTextAlignment="Center"
FontSize="Medium">
<Label.FormattedText>
<FormattedString>
<Span Text="{DynamicResource currentDateTime}" />
</FormattedString>
</Label.FormattedText>
</Label>-->
</StackLayout>
</ContentPage>
您可能希望对currentDateTime字典项的所有三个引用都导致显示文本“Not actual a DateTime”。 但是,代码隐藏文件启动计时器。 每秒,计时器回调用一个表示实际DateTime值的新字符串替换该字典项:
public partial class DynamicVsStaticPage : ContentPage
{
public DynamicVsStaticPage()
{
InitializeComponent();
Device.StartTimer(TimeSpan.FromSeconds(1),
() =>
{
Resources["currentDateTime"] = DateTime.Now.ToString();
return true;
});
}
}
结果是使用StaticResource设置的Text属性保持不变,而DynamicResource设置的Text属性每秒更改一次以反映字典中的新项:
这是另一个区别:如果字典中没有指定键名的项,静态?资源将引发运行时异常,但DynamicResource不会。
您可以尝试在DynamicVsStatic项目的末尾取消注释标记块,并且您确实会遇到无法找到Text属性的运行时异常。 只是随便,这个例外听起来不太正确,但它指的是一个非常真实的区别。
问题是Label和Span中的Text属性以明显不同的方式定义,而这种差异对DynamicResource很重要。 这种差异将在下一章“可绑定基础设施”中探讨。