如何以最佳、最可行的方式在元素内部存储数据?
我曾经使用单独的XML文件,现在我正在使用标签和工具提示属性。
这是一种字符串类型的数据,例如:
主题数据 Theme1.fg.ffffffff;Theme2.fg.ff000000;
根据窗口大小的边距 Margin.16:9.10,5,10,5;
使用 WPF/XAML,一个理想的方法是将这样的字符串存储在相应元素的 Resources
中或者在 ResourceDictionary
中。
例如:
<Grid x:Name="myGrid" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Grid.Resources>
<sys:String x:Key="ThemeData">Theme1.fg.ffffffff;Theme2.fg.ff000000;</sys:String>
<sys:String x:Key="Margins">Margin.16:9.10,5,10,5;</sys:String>
</Grid.Resources>
</Grid>
要使用相同的功能,您有两种方法
XAML 方法
<TextBlock Text="{StaticResource ThemeData}" />
代码后台
string themeData = myGrid.FindResource("ThemeData");
这些资源也可以存储在 ResourceDictionary
中,进而合并到任何元素、窗口甚至整个应用程序中。
例如:
StringResources.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:String x:Key="ThemeData">Theme1.fg.ffffffff;Theme2.fg.ff000000;</sys:String>
<sys:String x:Key="Margins">Margin.16:9.10,5,10,5;</sys:String>
</ResourceDictionary>
用法
<Grid x:Name="myGrid">
<Grid.Resources>
<ResourceDictionary Source="StringResources.xaml" />
</Grid.Resources>
<TextBlock Text="{StaticResource ThemeData}" />
</Grid>
或者如果您想合并/覆盖更多资源,可以使用这个选项
<Grid x:Name="myGrid">
<Grid.Resources>
<ResourceDictionary xmlns:sys="clr-namespace:System;assembly=mscorlib">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="StringResources.xaml" />
</ResourceDictionary.MergedDictionaries>
<!--define new resource or even override existing for this specific element -->
<sys:String x:Key="ThemeData">Theme1.fg.ff00ff00;Theme2.fg.ff0000ff;</sys:String>
<sys:String x:Key="NewMargins">Margin.16:9.10,5,10,5;</sys:String>
</ResourceDictionary>
</Grid.Resources>
<TextBlock Text="{StaticResource ThemeData}" />
</Grid>