WPF资源的基本概念
WPF資源系統是一種保管一系列對象(如常用的畫刷、樣式或模版)的簡單辦法,從而更容易地復用這些對象。
WPF允許在代碼中以及在標記中的各個位置定義資源(和特定的控件、窗口一起定義,或在整個應用程序中定義)。資源具有如下優點。
? ? 高效。定義好資源可以在多個地方復用。
? ? 可維護性。易于修改。
? ? 適應性。可以動態修改。
資源集合
每個元素都有Resources屬性,該屬性存儲了一個資源字典集合(它是ResourceDictionary類的實例)。資源集合可包含任意類型的對象,并根據字符串編寫索引。
可以將資源引用為靜態資源或動態資源。這可以通過使用StaticResource標記擴展或DynamicResource標記擴展來實現。
WPF中,每個界面元素都含有一個名為Resources的屬性,其存儲的是以“鍵-值”對形式存在的資源,而其子級元素在使用這些資源時會從Resources中找到這些資源。在子級元素引用的資源分為StaticResource和DynamicResource,兩者的不同在于,StaticResource在程序編譯完成后就不能改變,而DynamicResource在編譯完成后可以進行修改。
下面來看一個字符串資源的簡單示例;
<Window x:Class="test2.Window1"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"Title="test2" Height="300" Width="300"><Window.Resources><sys:String x:Key="str">這是一個字符串資源</sys:String></Window.Resources><Grid><TextBox Text="{StaticResource str}" Width="200" Height="40" HorizontalAlignment="Right"></TextBox><TextBox Height="50" HorizontalAlignment="Left" Name="textBox1" VerticalAlignment="Top" Width="200" Text="{DynamicResource str}"/><Button Content="獲取動態資源" Height="23" HorizontalAlignment="Left" Margin="167,243,0,0" Name="button1" VerticalAlignment="Top" Width="114" Click="button1_Click" /></Grid> </Window> using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media;namespace test2 {/// <summary>/// Interaction logic for Window1.xaml/// </summary>public partial class Window1 : Window{public Window1(){InitializeComponent();}private void button1_Click(object sender, RoutedEventArgs e){string strd = "我是動態資源, AAA";this.Resources["str"] = strd;}} }? ? 使用sharpdevelop;設計時如下;
運行單擊按鈕后如下;?
為了使用 sys 標簽,必須包含:xmlns:sys="clr-namespace:System;assembly=mscorlib"
有一個按鈕跑頂部去了,因為?VerticalAlignment="Top";
總結
以上是生活随笔為你收集整理的WPF资源的基本概念的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 初步了解WPF依赖属性
- 下一篇: WPF 路由事件初步