资源 - 图1image.png
优点:

  • 高效:通过资源定义对象,并在标记中的多个地方使用,精简代码
  • 可维护性

    资源字典

    应用:多个项目之间共享资源,可创建资源字典。资源字典只是XAML文档,只存储希望使用的资源。
    通常合并到Application中。定义一个或多个可重用的应用程序“皮肤”,可将“皮肤”应用到控件上。
    1. <Application x:Class="WpfPrj.App"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:local="clr-namespace:WpfPrj"
    5. StartupUri="MainWindow.xaml">
    6. <Application.Resources>
    7. <ResourceDictionary>
    8. <ResourceDictionary.MergedDictionaries>
    9. <!--This put ResourceDictionary Source="xxx.xaml"-->
    10. </ResourceDictionary.MergedDictionaries>
    11. <!--This put self resource-->
    12. </ResourceDictionary>
    13. </Application.Resources>
    14. </Application>

    静态、动态资源

    应用:重用 ```csharp
    1. <TextBlock x:Key="staticResource" Text="This is staticResouce"/>
    2. <TextBlock x:Key="dynamicResource" Text="This is dynamicResource"/>

private void update_Click(object sender, RoutedEventArgs e) { this.Resources[“dynamicResource”] = new TextBlock() { Text = “this is update” }; }

//C#代码 string text = (string)this.FindResource(“staticResource”);

  1. <a name="0pno6"></a>
  2. # 二进制资源(应用程序的内嵌资源)
  3. 应用:程序的国际化、本地化
  4. ```csharp
  5. xmlns:prop="clr-namespace:WpfPrj.Properties"
  6. <StackPanel Margin="0,0,0,-137">
  7. <TextBlock x:Name="textBlock" Text="{x:Static prop:Resources.Password}"/>
  8. </StackPanel>
  9. //C#代码
  10. this.textBlock.Text=Properties.Resources.Password;