WPF中的资源(一) - 静态资源和动态资源

来源:互联网 发布:ps软件电脑版 编辑:程序博客网 时间:2024/05/17 23:19

WPF中,每个界面元素都含有一个名为Resources的属性,其存储的是以“键-值”对形式存在的资源,而其子级元素在使用这些资源时会从Resources中找到这些资源。在子级元素引用的资源分为StaticResource和DynamicResource,两者的不同在于,StaticResource在程序编译完成后就不能改变,而DynamicResource在编译完成后可以进行修改,如下代码:

<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("资源键值");


0 0
原创粉丝点击