<Pro WPF 4.5 in C#> - Note-03

50 篇文章 0 订阅
5 篇文章 0 订阅

Chapter 10: Resources


Resource Basics


The Resources Collection

Every element includes a Resources property, which is an instance of the ResourceDictionary class. The resources collection can hold any type of object, indexed by string.

Because every element has access to the resources in its own resource collection and the resources in all of its parents' resource collections.most common way to define resources is at the window level.

<Window.Resources>
	<ImageBrush x:Key="TileBrush" />
</Window.Resources>

The first attribute, named Key, assigns the name under which the resource object will be indexed in the Window.Resources collection.


To use a resource, there are two markup extensions that you can use:

static resources

Static resources are set once, when the window is first created.

You must always define a resource in your markup before you refer to it.

<Button Background="{StaticResource TileBrush}" />


dynamic resources

Dynamic resources are reapplied if the resource is changed.


The Hierarchy of Resources

Every element has its own resource collection, and WPF performs a recursive search up your element tree to find the resource you want. It uses the resource it finds first.

<Button Margin="5" Padding="5" FontWeight="Bold" FontSize="14">
	<Button.Resources>
		<ImageBrush x:Key="TileBrush" TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 10 10" ImageSource="happyface.jpg" Opacity="0.3"></ImageBrush>
	</Button.Resources>
	<Button.Background>
		<StaticResource ResourceKey="TileBrush"/>
	</Button.Background>
	<Button.Content>Another Tiled Button</Button.Content>
</Button>


Static and Dynamic Resources

Whenever you change a brush in WPF, any controls that use that brush refresh themselves automatically. It doesn't matter whether they get their brushes through a resource.

The difference is that a static resource grabs the object from the resources collection once. Depending on the type of object (and the way it's used), any changes you make to that object may be noticed right away. However, the dynamic resource looks the object up in the resources collection every time it's needed. That means you could place an entirely new object under the same key, and the dynamic resource would pick up your change.

As a general guideline, use dynamic properties only when you have these conditions:

  • Your resource has properties that depend on system settings (such as the current Windows colors or fonts)
  • You plan to replace your resource objects programmatically


Nonshared Resources


Accessing Resources in Code

private void cmdChange_Click(object sender, RoutedEventArgs e)
{
	Button cmd = (Button)sender;
	ImageBrush brush = (ImageBrush)sender.FindResource("TileBrush");
	...
}

Application Resources

Application resources give you a great way to reuse an object across your entire application.

System Resources

In the System.Windows namespace

  • SystemColors gives you access to color settings
  • SystemFonts gives you access to font settings
  • SystemParameters wraps a huge list of settings that describe the standard size of various screen elements, keyboard and mouse settings, and screen size, and whether various graphical effects are switched on.

The secret is a set of three classes named SystemColors, SystemFonts, and SystemParameters, all of which expose all their details through static properties.



Resource Dictionaries

If you want to share resources between multiple projects, you can create a resource dictionary.


Creating a Resource Dictionary



Using a Resource Dictionary



Sharing Resources Between Assemblies

You can use a Type object as a key name for a style. This tells WPF to apply the style to the appropriate type of element automatically.

Your resource dictionary must be in a file named generic.xaml, and that file must be placed in a Themes subfolder in your application. The resources in the generic.xaml files are considered part of the default theme, and they're always made available.




Chapter 11: Styles and Behaviors


Style Basics

Thanks to the property value inheritance feature, when you set these properties at the window level, all the elements inside the window will acquire the same values, unless they explicitly override them.


<Window xmlns:sys="clr-namespace:System;assembly=mscorlib" ... >

	<Window.Resources>
		<FontFamily x:Key="ButtonFontFamily">Times New Roman</FontFamily>
		<sys:Double x:Key="ButtonFontSize">18</s:Double>
		<FontWeight x:Key="ButtonFontWeight">Bold</FontWeight>
	</Window.Resources>


	<Button Padding="5" Margin="5" Name="cmd"
		FontFamily="{StaticResource ButtonFontFamily}"
		FontWeight="{StaticResource ButtonFontWeight}"
		FontSize="{StaticResource ButtonFontSize}">
			A Customized Button
	</Button>

Simplify it with style:

<Window.Resources>
	<Style x:Key="BigFontButtonStyle">
		<Setter Property="Control.FontFamily" Value="Times New Roman" />
		<Setter Property="Control.FontSize" Value="18" />
		<Setter Property="Control.FontWeight" Value="Bold" />
	</Style>
</Window.Resources>

That creates an object of System.Windows.Style.

Every WPF element can use a single style (or no style). The style plugs into an element through the element's Style property (which is defined in the base FrameworkElement class).


<Button Padding="5" Margin="5" Name="cmd" Style="{StaticResource BigFontButtonStyle}">
	A Customized Button
</Button>

With C#

cmd.Style = (Style)cmd.FindResource("BigFontButtonStyle");


Styles set the initial appearance of an element, but you're free to override the characteristics they set.

PropertyDescription
Setters 
Triggers 
Resources 
BasedOn 
TargetType 


Creating a Style Object

You don't need to use styles and resources together. You could define the style of a particular button by filling its Style collection directly, as shown here:

<Button Padding="5" Margin="5">
	<Button.Style>
		<Style>
			<Setter Property="Control.FontFamily" Value="Times New Roman" />
			<Setter Property="Control.FontSize" Value="18" />
			<Setter Property="Control.FontWeight" Value="Bold" />
		</Style>
	</Button.Style>
	<Button.Content>A Customized Button</Button.Content>
</Button>


Setting Properties

The only limitation is that a setter can only change a dependency property.

In some cases, you won't be able to set the property value using a simple attribute string.

<Style x:Key="HappyTiledElementStyle">
	<Setter Property="Control.Background">
		<Setter.Value>
			<ImageBrush TileMode="Tile" ViewportUnits="Absolute" Viewport="0 0 32 32" ImageSource="happyface.jpg" Opacity="0.3">
			</ImageBrush>
		</Setter.Value>
	</Setter>
</Style>

To identify the property you want to set, you need to supply both a class and a property name.

Notice the "Button.Xxx":

<Style x:Key="BigFontButtonStyle">
	<Setter Property="Button.FontFamily" Value="Times New Roman" />
	<Setter Property="Button.FontSize" Value="18" />
	<Setter Property="Button.FontWeight" Value="Bold" />
</Style>

There are some cases in WPF where the same properties are defined in more than one place in the element hierarchy.Below code won't work:

<Style x:Key="BigFontStyle">
	<Setter Property="Button.FontFamily" Value="Times New Roman" />
	<Setter Property="Button.FontSize" Value="18" />
	<Setter Property="TextBlock.FontFamily" Value="Arial" />
	<Setter Property="TextBlock.FontSize" Value="10" />
</Style>


<Style x:Key="BigFontButtonStyle" TargetType="Button">
	<Setter Property="FontFamily" Value="Times New Roman" />
	<Setter Property="FontSize" Value="18" />
	<Setter Property="FontWeight" Value="Bold" />
</Style>


Attaching Event Handlers

<Style x:Key="MouseOverHighlightStyle">
	<EventSetter Event="TextBlock.MouseEnter" Handler="element_MouseEnter" />
	<EventSetter Event="TextBlock.MouseLeave" Handler="element_MouseLeave" />
	<Setter Property="TextBlock.Padding" Value="5"/>
</Style>


private void element_MouseEnter(object sender, MouseEventArgs e)
{
	((TextBlock)sender).Background = new SolidColorBrush(Colors.LightGoldenrodYellow);
}

private void element_MouseLeave(object sender, MouseEventArgs e)
{
	((TextBlock)sender).Background = null;
}


<TextBlock Style="{StaticResource MouseOverHighlightStyle}">
	Hover over me.
</TextBlock>


MouseEnter and MouseLeave use direct event routing, which means they don't bubble up or tunnel down the element tree.


If you need the functionality shown here, you're more likely to use event triggers, which define the action you want declaratively (and so require no code).

Event setters aren't a good choice when handling an event that uses bubbling.


The Many Layers of Styles

In other cases, you might want to create a style that builds upon another style.

<Window.Resources>
	<Style x:Key="BigFontButtonStyle">
		<Setter Property="Control.FontFamily" Value="Times New Roman" />
		<Setter Property="Control.FontSize" Value="18" />
		<Setter Property="Control.FontWeight" Value="Bold" />
	</Style>
	<Style x:Key="EmphasizedBigFontButtonStyle"
		BasedOn="{StaticResource BigFontButtonStyle}">
		<Setter Property="Control.Foreground" Value="White" />
		<Setter Property="Control.Background" Value="DarkBlue" />
	</Style>
</Window.Resources>

You can use the BasedOn property to create an entire chain of inherited styles. The only rule is that if you set the same property twice, the last property setter (the one in the derived class furthest down the inheritance chain) overrides any earlier definitions.


Automatically Applying Styles by Type

You simply need to set the TargetType property to indicate the appropriate type (as described earlier) and leave out the key name altogether. When you do this, WPF actually sets the key name implicitly using the type markup extension, as shown here:

x:Key="{x:Type Button}"

Now the style is automatically applied to any buttons all the way down the element tree.

You can explicitly replaces the style, like:

<Button Padding="5" Margin="5" Style="{x:Null}">A Normal Button</Button>


Triggers













Behaviors


Chapter 17: Control Templates


Understanding Logical Trees and Visual Trees



Understanding Templates



Creating Control Templates






Microsoft's Windows Presentation Foundation (WPF) provides you with a development framework for building high-quality user experiences for the Windows operating system. It blends together rich content from a wide range of sources and allows you unparalleled access to the processing power of your Windows computer. Pro WPF 4.5 in C# provides a thorough, authoritative guide to how WPF really works. Packed with no-nonsense examples and practical advice you'll learn everything you need to know in order to use WPF in a professional setting. The book begins by building a firm foundation of elementary concepts, using your existing C# skills as a frame of reference, before moving on to discuss advanced concepts and demonstrate them in a hands-on way that emphasizes the time and effort savings that can be gained. What you’ll learn •Understand the fundamentals of WPF programming from XAML to controls and data flow. •Develop realistic application scenarios to see navigation, localization and deployment in action. •Explore the advanced user interface controls that WPF provides. •Learn to manage documents from within WPF: Text layout, printing, and document packaging are all covered. •Use graphics and multimedia to add punch to your applications Who this book is for This book is designed for developers encountering WPF for the first time in their professional lives. A working knowledge of C# and the basic architecture of .NET is helpful to follow the examples easily, but all concepts will be explained from the ground up. Table of Contents 01.Introducing WPF 02.XAML 03.Layout 04.Dependency Properties 05.Routed Events 06.Controls 07.The Application 08.Element Binding 09.Commands 10.Resources 11.Styles and Behaviors 12.Shapes, Brushes, and Transforms 13.Geometries and Drawings 14.Effects and Visuals 15.Animation Basics 16.Advanced Animation 17.Control Templates 18.Custom Elements 19.Data Binding 20.Formatting 21.Bound Data 22.Data Views 23.Lists, Trees, and Grids 24.Windows Pages and Navigation 25.Menus, Toolbars, and Ribbons 26. Sound and Video 27.3-D Drawing 28.Documents 29. Printing 30.Interacting with Windows Forms 31.Multithreading 32.The Add-in Model 33.ClickOnce Deployment ----------------------------------------------------------- Pro WPF 4th edition,喜欢的朋友请支持正版。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值