WPF学习心得(1)
资源
WPF中的资源一般是指资源字典(DictionaryResource)中的元素,可以把任何对象置于其中以便访问。
要获得一个资源字典,可以新建:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</ResourceDictionary>
但更多的时候是通过Resources属性来获得的:
Application.Resources //整个应用程序有效
FramewrokElement.Resources //该控件及其子控件有效
Style.Resources //样式中有效
我举一个较为复杂的例子:
<Window x:Class="WpfApplication30.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
Title="Window1" Height="309" Width="345" >
<Window.Resources>
<SolidColorBrush Color="Green" x:Key="scBrush"/>
<Button Background="Gray" x:Key="btnKey" x:Name="btnName"/>
<s:Double x:Key="Double">47</s:Double>
</Window.Resources>
<StackPanel>
<Button Background="{StaticResource scBrush}"/>
<Button Background="{Binding Source={StaticResource scBrush}}"/>
<Button Background="{Binding Source={StaticResource btnKey},Path=Background}"/>
<Button Background="{Binding Background,ElementName=btnName}"/>
<Button Height="{StaticResource Double}"/>
<StaticResource ResourceKey="btnKey"/>
<Button Content="{x:Static s:Math.PI}"/>
</StackPanel>
</Window>
Window是一个FrameworkElement元素,实际上,在WPF中,几乎所有的控件都是FrameworkElement的派生,所以都有Resources属性。
DictionaryResource中的项需要一个Key来区分不同的元素(在后面讲到Style的时候,会有一个特例),而其Name则是可有可无的。
我在资源字典中定义了三个资源,包括两个WPF中的对象SoildColorBrush和Button,以及一个CLR对象浮点数,为了使用CLR中的类型,我事先引入了命名空间:
xmlns:s="clr-namespace:System;assembly=mscorlib"
该示例中,我使用了7种不同的方式创建了7个按钮,下面分别予以说明:
第一行:
<Button Background="{StaticResource scBrush}"/>
创建一个Button,并将其Background属性绑定到资源scBrush。
其中大括号{}表示这是一个标记扩展;
StaticResource表示引入静态资源,与之相对的,还有一个DynamicResource,这两者用法一样,区别也不大,简单地说,动态资源在运行时才绑定,并且当资源更改时可以发出通知,而且可以先使用,后声明;
scBrush是资源的键
该行实际上等价于
等二行:
<Button Background="{Binding Source={StaticResource scBrush}}"/>
也就是说,实际上是创建了一个Binding对象,并设置其Source属性为静态资源scBrush
第三行:
<Button Background="{Binding Source={StaticResource btnKey},Path=Background}"/>
这里也是设置Background属性,但与之前的不同,这里绑定的是一个按钮,而不是一个画刷,所以这里用Path属性来指定其路径
第四行:
<Button Background="{Binding Background,ElementName=btnName}"/>
我们也可以用Name而不是Key来访问资源,这需要把Source改为ElementName,另外,我还要告诉你,如果Path是绑定中的第一个对象,则可以省略”Path=”。
第五行:
<Button Height="{StaticResource Double}"/>
绑定CLR对象
第六行:
<StaticResource ResourceKey="btnKey"/>
这是一个迥然不同的语法,我没有使用Binding,而是直接嵌入资源。
这种语法也许十分罕见,以至于VisualStudio都无法给出正确的智能感知,我也是反复实验出来的,切勿模仿!(^_^)
第七行:
<Button Content="{x:Static s:Math.PI}"/>
原来绑定并不一定需要创建资源,你也可以通过x:Static的语法来使用静态属性。
总结一下:
通常,每个绑定都具有四个组件:绑定目标对象、目标属性、绑定源,以及要使用的绑定源中的值的路径。
举例如下:
<Button Background="{Binding Source={StaticResource btnKey},Path=Background}"/>
其中Button为绑定目标对象,Background为目标属性,btnKey(或者btnName)为绑定源,Path为绑定源路径。如何省略路径,则认为绑定的是整个绑定源。
当然,还有许多与绑定相关的东西还没有提到,比如绑定上下文、属性通知等,大家自己去看吧。