转自:
http://hi.baidu.com/wangjunwangjuna/blog/item/c9dd3e4e9c1209dad1c86a91.html
首先看一下静态资源和动态资源的示例,代码如下:
XAML代码如下:
<Window x:Class="WPF中的对象集合.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ImageBrush x:Key="MyBrush"
TileMode="Tile"
ViewportUnits="Absolute"
Viewport="0 0 30 30"
ImageSource="/image/1.png"
Opacity="0.9"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Name="btn_Message" Grid.Row="0" Background="{StaticResource MyBrush}">1111111111</Button>
<Button Grid.Row="1" Click="Button_Click">222222222222</Button>
<Button Grid.Row="2" Background="{DynamicResource MyBrush}">33333333</Button>
</Grid>
</Window>
CS代码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WPF中的对象集合
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Resources["MyBrush"] = new LinearGradientBrush(new GradientStopCollection()
{
new GradientStop()
{
Color=Colors.Red,
Offset=0.1
},
new GradientStop()
{
Color=Colors.Green,
Offset=0.5
},
new GradientStop()
{
Color=Colors.Blue,
Offset=0.9
}
});
}
}
}
从上面的示例中可以看到,当单击第二个按钮时,会将资源中的图像画刷更改为Linear画刷,这时动态资源会随之改变,而静态资源不会改变