天天看點

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中的動态資源和靜态資源使用,以圖檔資源為例