WPF学习笔记-资源基础

将已经定义好的资源,进行绑定,方便样式的更改。也分静态和动态资源。

静态资源加载一次在资源,资源变动后,不会更新绑定控件的资源。

动态资源,资源变动,绑定的控件资源也随着变动。

 1 <Window x:Class="WPFdemo7.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6         xmlns:local="clr-namespace:WPFdemo7"
 7         mc:Ignorable="d"
 8         Title="MainWindow" Height="350" Width="525">
 9     <Window.Resources>
10         <SolidColorBrush x:Key="BackGroudColor" Color="Yellow"></SolidColorBrush>
11     </Window.Resources>
12     <Grid>
13         <WrapPanel Margin="-10,0,10.4,-0.2" >
14             <Button x:Name="button1" Content="静态资源1" Width="78" Height="326" Background="{Binding Source={StaticResource BackGroudColor}}"/>
15             <Button x:Name="button2" Content="静态资源2" Width="78" Height="326" Background="{StaticResource BackGroudColor}"/>
16             <Button x:Name="button3" Content="静态资源3" Width="78" Height="326" >
17                 <Button.Background>
18                     <StaticResource ResourceKey="BackGroudColor"></StaticResource>
19                 </Button.Background>
20             </Button>
21             <Button x:Name="button4" Content="动态资源" Width="78" Height="326" >
22                 <Button.Background>
23                     <DynamicResource ResourceKey="BackGroudColor"></DynamicResource>
24                 </Button.Background>
25             </Button>
26             <Button x:Name="button5" Content="改变资源颜色" Width="78" Height="97" Click="button5_Click" >
27                 </Button>
28 
29 
30         </WrapPanel>
31     </Grid>
32 </Window>
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Windows;
 7 using System.Windows.Controls;
 8 using System.Windows.Data;
 9 using System.Windows.Documents;
10 using System.Windows.Input;
11 using System.Windows.Media;
12 using System.Windows.Media.Imaging;
13 using System.Windows.Navigation;
14 using System.Windows.Shapes;
15 
16 namespace WPFdemo7
17 {
18     /// <summary>
19     /// MainWindow.xaml 的交互逻辑
20     /// </summary>
21     public partial class MainWindow : Window
22     {
23         public MainWindow()
24         {
25             InitializeComponent();
26         }
27 
28       
29         private void button5_Click(object sender, RoutedEventArgs e)
30         {
31             this.Resources["BackGroudColor"] = new SolidColorBrush(Colors.Blue);
32         }
33     }
34 }
View Code

效果图:

 

 

方法一:使用this.resource["资源名"];

方法二:this.findresource("资源名");

方法三:this.tryfindresource("资源名");

方法一和其他方法区别:resource仅元素本身的资源,其他的可以通过向上遍历访问资源。

方法二和方法三区别:方法二找不到资源会报异常。方法三找不到资源放回空值。

posted @ 2020-05-21 22:19  安以痕_陈  阅读(174)  评论(0编辑  收藏  举报