元素中存储数据的最佳、最可能proper
方法是什么?
我曾经使用单独的XML
文件,现在我使用的是 Tag
和 tooltip
属性。
它是一个字符串类型的数据,例如:
主题数据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>
我的理解是,您可以使用控件上的 Tag 属性来存储信息。 它接受对象类型。 因此,您可以将任何类型附加到它。 比如控制。标签 = 要附加的对象。如果我的回答似乎不相关,请详细说明您的问题