1、新建一个wpf工程
2、创建之后,右键删除App.xaml和MainWindow.xaml
3、更改工程属性中输出类型为:类库,搞定
4、创建一个新的“wpf自定义控件”项目,然后随便添加一个图片作为示例资源。
文件结构如下:
资源字典文件(background.xaml)里面的代码如下:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Resource">
<ImageBrush x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:CustomControl1},ResourceId=test}" ImageSource="pack://application:,,,/Resource;component/Lighthouse.jpg"></ImageBrush>
</ResourceDictionary>
因为这个资源是要作为共享资源的,所以这里要使用绝对 pack URI路径
(2)资源配置
1.资源合并
如果你创建了多个资源字典作为共享资源的话,进行资源合并就是必须的,资源合并的代码写在Generic.xaml里:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Resource">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Resource;component/background.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
这里的重点也和上面一样,要使用绝对url路径
2.类文件
这一步其实可以是可选的,但加上之后可以简化资源的使用,因此也是用必要的
public class CustomControl1
{
public static ComponentResourceKey test
{
get
{
return new ComponentResourceKey(typeof(CustomControl1), "test");
}
}
}
3)资源使用
资源准备好之后就可以使用了
1.命名空间包含
使用之前要先包含命名空间:
xmlns:res="clr-namespace:Resource;assembly=Resource"
2.使用
直接在控件里使用:
<Button MinHeight="100" Background="{DynamicResource {x:Static res:CustomControl1.test}}"></Button>