WPF中的資源(一) - 靜態資源和動態資源

原文: WPF中的資源(一) - 靜態資源和動態資源

WPF中,每一個界面元素都含有一個名爲Resources的屬性,其存儲的是以「鍵-值」對形式存在的資源,而其子級元素在使用這些資源時會從Resources中找到這些資源。在子級元素引用的資源分爲StaticResource和DynamicResource,二者的不一樣在於,StaticResource在程序編譯完成後就不能改變,而DynamicResource在編譯完成後能夠進行修改,以下代碼:
css

<Window x:Class="_9_4.MainWindow"
        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="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <sys:String x:Key="str">
            這a是º?一°?個?資Á¨º源¡ä裏¤?的Ì?字Á?符¤?串ä?
        </sys:String>
    </Window.Resources>
    <Grid>
        <TextBox Text="{StaticResource str}" Margin="129,56,189,206">
        </TextBox>
        <TextBox Height="53" HorizontalAlignment="Left" Margin="129,142,0,0" Name="textBox1" VerticalAlignment="Top" Width="185" 
                 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>

後臺代碼:

/// <summary>
    /// MainWindow.xaml 的Ì?交?互£¤邏?輯-
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string strd = "我¨°變À?成¨¦了¢?動¡¥態¬?資Á¨º源¡ä";
            this.Resources["str"] = strd;
        }

效果以下:



在後臺查找資源的兩種方法:this.Resources["資源鍵值"]和this.FindResource("資源鍵值");html

相關文章
相關標籤/搜索