天天看点

WPF中的动态资源和静态资源使用,以图片资源为例

首先来看一下效果,label1的背景是以静态方式绑定的图片,label2的背景是以动态方式绑定的同一张图片。点击按钮“更换背景”之后,label2的背景就变成蓝色了,如下图:

WPF中的动态资源和静态资源使用,以图片资源为例
WPF中的动态资源和静态资源使用,以图片资源为例

MainWindow.xaml中代码如下:

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication3"
        mc:Ignorable="d"
        Title="MainWindow" Height="365.2" Width="185">
    <Window.Resources>
        <ImageBrush x:Key="backGroundImg" ImageSource="Image/search.png"></ImageBrush>
    </Window.Resources>
    <Grid Name="mainGrid">
        <Grid.RowDefinitions>
            <RowDefinition Height="118*"/>
            <RowDefinition Height="108*"/>
            <RowDefinition Height="51*"/>
        </Grid.RowDefinitions>
        <Label Name="label1" Background="{StaticResource backGroundImg}" Content="Label1" Grid.Row="0" Margin="0,0,0,0.4"></Label>
        <Label Name="label2" Background="{DynamicResource backGroundImg}" Content="Label2" Grid.Row="1" Margin="0,0.6"/>
        <Button Name="Btn2" Content="更换背景" Grid.Row="2" Click="Btn2_Click"/>
    </Grid>
</Window>
           

按钮绑定的点击事件响应函数如下:

private void Btn2_Click(object sender, RoutedEventArgs e)
{
    //this.mainGrid.Resources["backGroundImg"] = new SolidColorBrush(Colors.Blue);
    this.Resources["backGroundImg"] = new SolidColorBrush(Colors.Blue);
}
           

解决方案中新建了一个Image文件夹,里面添加了一个图片,如下图:

WPF中的动态资源和静态资源使用,以图片资源为例