08.11.2011 18:48:27
WPF4_.indd 1
WPF4
Unleashed
Adam Nathan
WPF4
-
2011
WPF 4.
.
.
.
.
.
. , .
.
.
WPF 4. . . . .: -, 2011.
880., .
ISBN 978-5-93286-196-7
Windows Presentation Foundation (WPF) Windows-.
, . WPF
, , , , ,
, .
, WPF,
, .
XAML ;
WPF: , ,
, , , , ;
: ,
, , XAML,
Visual State Manager, ;
, , ;
, ,
,
, Visual Studio; ,
WPF;
, WPF Windows Forms, DirectX
ActiveX; , WPF-
Windows 7, ,
WPF .
ISBN 978-5-93286-196-7
ISBN 978-0-672-33119-0 ()
-, 2011
Authorized translation of the English edition 2010 Pearson Education. This trans
lation is published and sold by permission of Pearson Education, the owner of all rights
to publish and sell the same.
,
.
, , .
-.199034,-,16,7,
.(812) 380-5007, www.symbol.ru. N 000054 25.12.98.
04.11.2011. 70100 1/16. 55 ..
19
I. 27
1. WPF Silverlight? 29
30
WPF 32
WPF 35
WPF3.5 WPF3.5 SP1 36
WPF4 38
Silverlight 40
42
2. XAML 43
XAML 45
47
48
51
52
55
58
Content 58
59
61
XAML 63
XAML 63
XAML 67
XAML2009 72
73
74
75
75
76
76
77
XAML 77
78
81
XAML 82
86
XML 88
XamlServices 89
XAML 92
96
1: XML , 97
2: , XML,
97
3. WPF 98
98
100
106
107
109
111
113
117
121
4. ,
125
126
Height Width 126
Margin Padding 128
Visibility 131
132
132
133
FlowDirection 134
135
RotateTransform 137
ScaleTransform 139
SkewTransform 141
TranslateTransform 142
MatrixTransform 142
143
7
144
5. 146
Canvas 147
StackPanel 150
WrapPanel 152
DockPanel 154
Grid 158
162
GridSplitter 165
166
Grid 169
171
TabPanel 171
ToolBarPanel 171
ToolBarOverflowPanel 171
ToolBarTray 171
UniformGrid 172
SelectiveScrollingGrid 172
173
173
175
177
: , ,
182
192
6. : , ,
193
193
194
195
196
200
202
205
MouseEventArgs 206
207
208
209
StylusDevice 210
210
211
212
, ,
216
224
225
228
229
230
7. 231
Windows 231
Window 232
Application 235
242
243
246
: ClickOnce
Windows 247
Windows 249
249
252
258
- 261
XAML- 263
265
268
268
XAML- 271
272
8. Windows 7 273
273
JumpTask 275
JumpPath 282
287
287
288
289
290
Aero Glass 292
TaskDialog 296
299
III. 301
9. 303
305
Button 306
RepeatButton 307
ToggleButton 308
CheckBox 308
RadioButton 309
311
Label 311
ToolTip 312
Frame 314
316
GroupBox 316
Expander 318
318
10. 319
320
DisplayMemberPath 321
ItemsPanel 322
325
325
ComboBox 326
ListBox 332
ListView 335
TabControl 336
DataGrid 337
345
Menu 345
ContextMenu 347
349
TreeView 349
ToolBar 351
StatusBar 354
355
11. , 356
Image 356
Text Ink 358
TextBlock 360
TextBox 362
RichTextBox 364
10
PasswordBox 364
InkCanvas 365
367
367
378
380
383
ProgressBar 384
Slider 385
386
Calendar 386
DatePicker 388
389
IV. 391
12. 393
393
394
395
400
402
406
406
411
413
13. 414
Binding 414
Binding 414
Binding XAML 417
.NET 419
420
422
DataContext 426
428
428
431
434
440
440
443
446
447
11
449
451
XmlDataProvider 452
ObjectDataProvider 456
459
459
461
466
: Twitter XAML 469
471
14. , , 472
473
475
481
488
489
490
492
- 493
500
505
514
517
524
, 524
525
529
V. 531
15. 533
Drawing 534
Geometry 537
Pen 548
550
Visual 552
DrawingVisual 553
Visual 556
Visual 559
Shape 566
Rectangle 568
Ellipse 569
12
Line 570
Polyline 571
Polygon 572
Path 572
, Shape 573
575
575
584
592
594
597
RenderTargetBitmap 597
BitmapCache 598
BitmapCacheBrush 601
601
16. 602
603
607
Position 608
LookDirection 611
UpDirection 614
OrthographicCamera PerspectiveCamera 617
Transform3D 620
TranslateTransform3D 623
ScaleTransform3D 623
RotateTransform3D 627
Transform3D 630
Model3D 631
Light 632
GeometryModel3D 639
Model3DGroup 654
Visual3D 656
ModelVisual3D 656
UIElement3D 658
Viewport2DVisual3D 660
662
Viewport3D 663
666
Visual.TransformToAncestor 666
Visual3D.TransformToAncestor Visual3D.
TransformToDescendant 670
674
13
17. 675
676
676
677
685
XAML- 690
690
698
699
700
702
703
706
706
707
708
710
712
716
720
18. , 722
722
SoundPlayer 723
SoundPlayerAction 724
MediaPlayer 724
MediaElement MediaTimeline 725
727
MediaElement 728
730
734
734
737
743
VI. 745
19. 747
Win32
WPF- 750
Win32 Webcam 750
Webcam WPF 753
760
14
WPF
Win32- 764
HwndSource 765
768
WindowsForms
WPF- 772
PropertyGrid 773
PropertyGrid XAML 775
WPF
Windows Forms 777
DirectX WPF 781
ActiveX
WPF- 788
792
20.
794
796
796
799
802
804
806
806
813
817
824
21. 825
826
826
828
SimpleCanvas 830
SimpleStackPanel 834
OverlapPanel 837
FanCanvas 842
847
848
3.
3.
3.
,
.
, ,
. ,
. , !
, ,
,
.
.
(Dwayne Need),
WPF, .
. (Robert
Hogue), (Joe Castro) (Jordan Parker)
. (David Teitlebaum),
WPF,
3D-
, (Daniel Lehenba
uer).
, ,
.
( ):
(Brian Chapman), (Beatriz de Oli
veira Costa), (Ifeanyi Echeruo), (Dan Glick),
17
3.
, , .
, ,
, . ,
, .
,
. ,
, .
, ,
-
.
, ,
.
, .
: feedback@samspublishing.com
:
3.
Neil Rowe
Executive Editor
Sams Publishing
800 East 96th Street
Indianapolis, IN 46240 USA
infor
mit.com/register, ,
.
20
, ,
WPF, ,
, ,
,
. ,
, ,
, .
, WPF 3.5, WPF 3.5 SP1 WPF 4,
, WPF.
, , WPF
, ,
.
,
Windows. ,
: ,
, ,
. ,
, .NET Framework.
, WPF,
.
.
WPF Silverlight
, , ,
Windows Phone 7 -.
,
,
, Microsoft Expression Blend.
. :
, XML eXten
sible Application Markup Language (XAML)
, .
WPF: , , ,
, , , .
21
, ,
, XAML, Visual State Manager,
..
, :
, , , .
, , ,
.
,
, Visual Studio.
, ,
,
.
, WPF.
, WPF
Windows Forms, DirectX, ActiveX .
, WPF- Win
dows7, ,
WPF .
, WPF
( , XML Paper Specification (XPS)
). , ,
, . ,
.
, , XAML C#;
C++/CLI.
XAML :
; ,
XAML, ,
; WPF
XAML, ; , XAML
, .NET- : Visual Basic, C#
-. , XAML C# ,
.
Windows Presentation
Foundation 4.0, Windows SDK Visual Studio 2010.
:
22
, ,
http://informit.com/title/9780672331190 http://adamnathan.
net/wpf.
,
, WPF.
,
, .
.
I
:
1 WPF Silverlight?
2 XAML
3 WPF
1 WPF ,
, . 2
XAML
23
XAML-, .
3
WPF, , ,
.NET.
II WPF-
:
4 ,
5
6 : , ,
7
8 Windows 7
II ,
( ,
, Aero Glass). 4
5 ( )
. 6
, .
7
WPF
.
Windows7,
.
III
:
9
10
11 ,
III , WPF.
, .
1
, .
11.
1
(content control
items control) , -
. content control
Content, items control
Items. ,
Microsoft, . .
.
24
IV
:
12
13
14 , ,
, IV,
WPF-,
.
,
. ,
,
.
V
:
15
16
17
18 ,
WPF,
. ,
, . ,
.
WPF . WPF
, ,
, !
VI
:
19
20 1
21
VI ,
WPF- .
WPF
,
.
1
Microsoft . . .
25
, :
, -
,
.
FAQ
FAQ?
,
, .
. ,
.
, ,
,
.
,
,
, .
I
I.
1 WPF Silverlight?
2 XAML
3 WPF
WPF
WPF
Silverlight
WPF
Silverlight?
1.
,
.
, - ,
.
, .
1994 Disclosure
() . ,
, , Microsoft Outlook!
:
; ,
;
. (
.
.)
,
, ,
. , ,
.
!
(, Windows ), -, ,
iPhone, iPad, Zune, TiVo, Wii, Xbox, Windows Phone -
. , -
,
.
, . -
30
1. WPF Silverlight?
.
.
:
,
, ,
. ,
,
.
, ,
. Win32 ,
, ,
.
2006 Microsoft ,
XXI ,
. Windows Presentation Foundation (WPF).
WPF4 2010
. ,
(Minority Report),
( iPhone), WPF4
Windows7 .
- !
Windows
(Graphics Device Interface, GDI) USER
Windows1.0 1985.
! 1990- Silicon
Graphics OpenGL
Windows, .
,
,
. Microsoft DirectX, 1995,
2D-, ,
, , 3D- (
DirectX 2, 1996).
GDI, DirectX
. , GDI+, Windows XP,
31
.
, GDI.
DirectX (, Xbox),
,
. .NET ( 2002)
Windows -. Windows Forms (
GDI+)
Windows C#, Visual Basic ( )
++. ,
, GDI+
USER.
DirectX 9 Microsoft
( ,
Visual Basic), XNA
Framework. # DirectX
, .NET COM,
.
XNA Framework,
, XNA Framework Content Pipeline XNA Game Studio Express.
, Windows 3D-
( ) 90-
GDI ( DirectX
OpenGL GDI),
. : ,
,
;
; GDI .
, , WPF
.
,
.
.
,
.
,
.
32
1. WPF Silverlight?
WPF
Microsoft , ,
GDI+ USER,
, Windows Forms.
, HTML Java
Script, Windows ,
. Windows Presentation Foundation (WPF)
,
. Presentation ()
,
,
, ,
, WPF!
, WPF.
. WPF Windows,
3D-, ,
, ,
. WPF
,
.
,
.
.
,
, .
!
, ,
! WPF
. , WPF
.
. WPF Direct3D,
WPF-,
, ,
, Direct3D,
. , WPF-
,
(
).
WPF
33
WPF ( ). WPF
.
.
,
(,
).
(,
, ,
GPU , , ).
.
WPF,
Win16/Win32
25 . .NET-
XML-. WPF
XAML (eXtensible Application Markup Language
) ( ). WPF XAML
HTML
, .
. WPF
XAML ,
3D- .
; , , .
XAML .
. WPF
.
, ,
, ! ,
, ,
, ,
(!) ( ,
). ,
, WPF
() ( 14 ,
, ).
, WPF , DirectX
( ), Windows Forms (
), Adobe Flash ( ) HTML (
). , , WPF
,
, , !
34
1. WPF Silverlight?
GDI
GDI Windows XP
.
GDI. Windows Vista
GDI.
GDI . Win
dows7 GDI.
FAQ
WPF -, ?
, . #, .NET , .
, !
WPF- WPF,
, , WPF
. , WPF Windows7, XAML (. 8 Windows7).
, .
FAQ
DirectX WPF?
DirectX
3D-, . , , DirectX,
WPF-.
DirectX , . Di
rectX :
, GPU, . ,
. , DirectX
GPU, , WPF.
WPF
35
, WPF .
, , . ( , ,
.) WPF , 2D
DirectX.
, DirectX, .
GPU, .
WPF ,
Microsoft ! , . , WPF- GPU , .
, WPF DirectX . 19 ,
.
WPF
, WPF4
WPF. , 3.0!
2006 WPF3.0,
.NET Framework3.0. WPF3.5
( , ).
( 2008).
Service Pack 1 (SP1) .NET3.5, WPF
, .
2008 http://wpf.codeplex.com
Microsoft WPF Toolkit,
. WPF Toolkit
, , (
). ,
WPF Toolkit, WPF
.
WPF
.
WPF- Visual Studio 2005,
Expression Blend .
Visual Studio 2010 WPF,
WPF-!
36
1. WPF Silverlight?
, WPF .
WPF
37
- .
, ,
(pixel shaders). . 15
.
WPF
,
,
. WriteableBitmap
,
, ! ,
,
.
,
(
(IME) ).
TextBox RichTextBox. . 11
, .
.NET-
,
WCF (Windows Communication Foun
dation) - ( basicHttpBinding)
cookie. , XAML Browser
Applications (XBAPs) WPF-
, Internet Explorer,
Firefox (
).
.NET
:
.NET ,
.NET, (,
ASP.NET); -,
.NET,
;
ClickOnce.
WPF
,
WPF- .
, ( ),
( ) ,
,
( 8)
. ,
-
38
1. WPF Silverlight?
,
(. 10
).
WPF4
WPF4 :
, Windows7
, WPF :
, (,
) ( ) .
WPF
. WPF
Microsoft Surface (,
, WPF).
WPF4 2 Surface SDK,
, Windows
Surface. . 6 : , ,
.
Windows7
, Windows 7,
, ,
, . WPF
, (Jump List)
(icon overlays),
. . 8.
WPF4
, DataGrid, Calendar DatePicker,
WPF Toolkit. . 11.
, BounceEase, ElasticEase SineEase,
.
Silverlight 3 WPF4.
Visual State Manager
Silverlight 2;
: .
, Expression Blend,
WPF Silverlight.
WPF
39
WPF
( )
(
, ).
WPF SnapsToDevicePixels,
.
,
. Silverlight ,
, UseLayoutRounding,
. WPF4.
true ,
(
), .
, !
WPF
,
96 (DPI).
. , ,
WPF, . WPF4
- ,
, ,
GDI, WPF.
, Visual Studio 2010
.
, . . 11.
.NET
.NET ,
WPF-. .NET 4.0 Visual
Studio 2010
.
WPF
.
CacheMode; . 15.
, WPF Visual Studio 2010,
WPF-.
40
1. WPF Silverlight?
FAQ
WPF 4?
,
,
Silverlight - WPF. ,
, WPF Toolkit. , BreadcrumbBar, NumericUp
Down .
FAQ
WPF Windows?
WPF API, Windows7
( ), , 8. , WPF Windows XP ( Windows, WPF).
, 3D-.
, , WPF
(Aero Windows Vista
Windows7, Luna Windows XP).
, Windows XP , WPF-.
Windows ,
, . WPF DirectX Windows XP , Windows .
Silverlight
Silverlight , .NET,
- ( Adobe Flash Flex).
Silverlight ,
WPF, . Silverlight 2007
, , WPF, . Silverlight4
2010, WPF4.
WPF Silverlight ,
, , .
, WPF-
( XBAPs),
Silverlight
41
. , Silverlight
, .
, Silverlight WPF
.NET Framework (
, ..). Silver
light WPF.
WPF .NET -
Silverlight, ,
WPF .NET.
, .NET. -
WPF .NET Framework
(, Visual State Manager
), ( ). , WPF
.NET , Silverlight, ,
.
, : WPF Silver
light?, .NET ?.
,
.NET, . WPF.
,
Mac , ,
Silverlight. Silverlight
(
HTML).
.
. (
)
, ,
Windows Mac.
, - , ,
WPF, Silverlight, .
Silverlight , ,
WPF, #ifdef.
Silverlight WPF,
.
(), WPF Silverlight
. , Silverlight ,
Windows Presentation Foundation,
.
Silverlight WPF
. Microsoft
. Microsoft
,
,
42
1. WPF Silverlight?
( ),
(Visual Studio, Expression Blend ..)
, , ( .NET # VB XAML) .
WPF Silverlight. ,
, , , , ,
, WPF, Silverlight.
,
, , ,
.
( Windows) .
WPF
, Windows-
( ) ,
.
,
.
. , !
XAML
XAML
XAML2009
XAML
XAML
2
2.
XAML
XML .NET
, .
XAML ( XML), WPF 2006
, .
, - HTML. ,
, , XAML ,
.
WPF Silverlight XAML
( ).
Windows Workflow Foundation (WF) Windows Communication Foun
dation (WCF) XAML
, .
XAML ,
.
XAML , ,
-
. XAML ( XML)
, , ,
.
WPF Silverlight
,
, Expression Blend,
, .
XAML, ,
, API,
.
44
2. XAML
(,
) .
, ,
XAML :
XAML
.
XAML
, ,
.
XAML ,
Visual Studio, Expression Blend -
,
.
XAML ,
WPF.
XAML
, .
, - .
,
, , API ,
. WPF-
, , , XAML,
XAML
(
, ), :
.xaml Inter
net Explorer ( Windows Vista Windows XP
.NET 3.0 ).
Firefox, .
WPF,
, WPF 4.
-
, XAMLPAD2009,
, Kaxaml (http://kaxaml.com),
WPF4.
WPF- Visual Studio
Window Page ;
.
XAML . XAML
Visual Studio .
XAML
45
,
XAML- (, ,
, ..).
FAQ
XamlPad?
Windows SDK XamlPad,
( ) WPF- XAML
, .
, . (,
, Microsoft
!)
XAML, :
XAMLPAD2009 .
, , .
, , XAML2009
( ).
Kaxaml , (Robby In
gebretsen), WPF;
http://kaxaml.com.
XamlPadX , http://blogs.
msdn.com/llobo/archive/2008/08/25/xamlpadx-4-0.aspx.
(Lester Lobo), WPF.
XAML Cruncher ClickOnce-,
http://charlespetzold.com/wpf/XamlCruncher/ XamlCruncher.application.
(Charles Petzold),
.
XAML
XAML
,
. XAML XML
, ,
, ( ).
XAML API
.NET, HTML, SVG (Scalable Vector Gra
phics) -
. XAML XML
, ,
. XAML
WPF C#
.NET Framework. Microsoft
46
2. XAML
XAML, .
, WPF XAML, Silverlight XAML
XAML-.
XAML XAML
XAML XAML :
XAML Object Mapping Specification 2006 (MS-XAML): http://go.microsoft.com/
fwlink/?LinkId=130721
WPF XAML Vocabulary Specification 2006 (MS-WPFXV): http://go.microsoft.
com/fwlink/?LinkId=130722
Silverlight XAML Vocabulary Specification 2008 (MS-SLXV): http://go.micro
soft.com/fwlink/?LinkId=130707
XAML WPF ,
, WPF XAML
. XAML WPF,
.
XAML -
. , XAML WPF-
. , XAML,
.NET- (
). - XAML,
, WPF-,
.
XAML,
, XAML,
.
12 14.
.
FrameworkElementFactory,
.
x:Shared="False", WPF
.
.
XAML-.
47
XAML ,
, .NET ,
XML. ( ) XAML, WPF- Button, C#:
XAML:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Content="OK"/>
C#:
System.Windows.Controls.Button b = new System.Windows.Controls.Button();
b.Content = "OK";
, XAML
Internet Explorer ,
(.2.1), C#
.
XML- XAML- (
) .NET
.
(
)
( ). ,
Content, Click.
XAML:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Content="OK" Click="button_Click"/>
48
2. XAML
C#:
System.Windows.Controls.Button b = new System.Windows.Controls.Button();
b.Click += new System.Windows.RoutedEventHandler(button_Click);
b.Content = "OK";
, - button_Click
, XAML-
, .2.1. XAML
, XAML-,
. , XAML, C#, .
, XAML- (
Name,
).
XAML.
. , ,
.NET
,
.
XAML-
# XML http://schemas.microsoft.com/
winfx/2006/xaml/presentation .NET System.Windows.Cont
rols. WPF
WPF,
XmlnsDefinitionAttribute. ( , URL-
schemas.microsoft.com -,
, .)
XAML-
XML;
.
XML ( ) ,
,
. , XAML-
WPF x
( xmlns:x, xmlns):
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
49
XAML,
System.Windows.Markup; ,
XAML. , XML-,
,
. XAML
XAML .
.NET
WPF WPF
.NET XML, WPF (http://
schemas.microsoft.com/winfx/2006/xaml/presentation):
System.Win
dows
System.Win
dows.Automation
System.Win
dows.Controls
System.Win
dows.Controls.Primitives
System.Win
dows.Data
System.Win
dows.Documents
System.Win
dows.Forms.Integration
System.Win
dows.Ink
System.Win
dows.Input
System.Win
dows.Media
System.Win
dows.Media.Animation
System.Win
dows.Media.Effects
System.Win
dows.Media.Imaging
System.Win
dows.Media.Media3D
System.Win
dows.Media.TextFormatting
System.Win
dows.Navigation
System.Win
dows.Shapes
System.Win
dows.Shell
--, WPF
,
.
50
2. XAML
<WpfNamespace:Button
xmlns:WpfNamespace="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Content="OK"/>
,
XML ( ) ,
.
XAML ,
, WPF
XML (http://schemas.microsoft.com/winfx/2006/xaml/presentation)
, XAML (http://schemas.microsoft.com/winfx/
2006/xaml) , x. , ,
XAMLPAD2009, .
WPF XML
XAML- WPF
WPF XML, ,
WPF, System.Windows , XML.
WPF3.0 http://schemas.microsoft.
com/winfx/2006/xaml/presentation, WPF3.5
XML http://schemas.microsoft.com/netfx/2007/xaml/presentation,
WPF. ( ,
WinFX , .NET 3.0:
WPF, WCF WF. ,
.) WPF4
XML, WPF: http://schemas.
microsoft.com/netfx/2009/xaml/presentation.
,
http://schemas.microsoft.com/winfx/2006/xaml/presen
tation, WPF. ( ,
XAML- WPF;
, WPF 3.0)
, Silverlight http://schemas.micro
soft.com/winfx/2006/xaml/presentation, Silver
light- XAML-, WPF. Silverlight
http://schemas.microsoft.
com/client/2007, WPF.
51
XML .
, . - ,
.
WPF
/ . , winfx/2006
3.0 ,
netfx/2007 3.5 .. WPF4
netfx/2009
/, - (
, TextOptions) !
XAML- Internet Explorer
PresentationHost.exe, , .NET
Framework , XML
. netfx/2009, 4.0,
3., .
,
WPF .
, .2.1,
, ! ,
,
:
System.Windows.Controls.Button b = new System.Windows.Controls.Button();
System.Windows.Shapes.Rectangle r = new System.Windows.Shapes.Rectangle();
r.Width = 40;
r.Height = 40;
r.Fill = System.Windows.Media.Brushes.Black;
b.Content = r; // Button
52
2. XAML
.2.2. Button
,
:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button.Content>
OK
</Button.Content>
<Button.Background>
White
</Button.Background>
</Button>
, XAML-
.
#-, Button:
Content Background:
53
! "White" XAML-
System.Windows.Media.Brushes.White (
System.Windows.Media.SolidColorBrush)? ,
, XAML-
, System.String System.Object.
XAML
, .
WPF
: Brush, Color, FontWeight, Point .. ,
TypeConverter (BrushConverter, ColorConverter ..)
.
XAML, .
Brush, XAML-
Background
:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Content="OK">
<Button.Background>
<SolidColorBrush Color="White"/>
</Button.Background>
</Button>
, Color
"White". ,
:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Content="OK">
<Button.Background>
<SolidColorBrush>
<SolidColorBrush.Color>
<Color A="255" R="255" G="255" B="255"/>
</SolidColorBrush.Color>
</SolidColorBrush>
</Button.Background>
</Button>
,
"255" Byte,
A, R, G B Color. , .
XAML- , ,
.
54
2. XAML
#, Background System.
Windows.Media.Brushes.White, , XAML-,
"White",
. ,
, :
System.Windows.Controls.Button b = new System.Windows.Controls.Button();
b.Content = "OK";
b.Background = (Brush)System.ComponentModel.TypeDescriptor.GetConverter(
typeof(Brush)).ConvertFromInvariantString("White");
#, "White"
, ,
XAML. ( Visual Studio XAML-
.)
- XAML
? ,
System.
ComponentModel.TypeConverterAttribute.
, Background Button XAML-
BrushConverter, Background
System.Windows.Media.Brush, :
[TypeConverter(typeof(BrushConverter)), ...]
public abstract class Brush : ...
{
...
}
, FontSize FontSizeConverter, (
Control) :
[TypeConverter(typeof(FontSizeConverter)), ...]
public double FontSize
{
get { ... }
set { ... }
}
,
(double)
FontSizeConverter . WPF double
LengthConverter.
55
, ,
XAML.
(
,
) ,
.
WPF .
, , XAML
.
. ,
, ,
. ,
, , BrushConverter
.
{},
XAML ,
( -, ).
Button
:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="{x:Null}"
Height="{x:Static SystemParameters.IconHeight}"
Content="{Binding Path=Height, RelativeSource={RelativeSource Self}}"/>
,
MarkupExtension.
Extension, XAML . Null
Extension ( x:Null) StaticExtension ( x:Static)
System.Windows.Markup,
x. Binding (
Extension) System.Windows.Data,
XML,
.
,
, . (
, SystemParameters.IconHeight)
.
56
2. XAML
( Path RelativeSource)
.
( ,
RelativeSource) ,
. .NET (
), , ,
XAML
. .
Button NullExtension
Background ( Background) null,
BrushConverter (, , )
. ,
null . StaticExtension
XAML , ,
. Height
Button
,
IconHeight System.Windows.SystemParameters. Binding
13 .
Content , Height.
, ,
. ,
, :
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Content="{}{ !}"/>
, , .
,
. :
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button.Content>
{ !}
</Button.Content>
</Button>
(. 13) , .
57
, .
Button :
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Button.Background>
<x:Null/>
</Button.Background>
<Button.Height>
<x:Static Member="SystemParameters.IconHeight"/>
</Button.Height>
<Button.Content>
<Binding Path="Height">
<Binding.RelativeSource>
<RelativeSource Mode="Self"/>
</Binding.RelativeSource>
</Binding>
</Button.Content>
</Button>
,
,
( ).
, StaticExtension Member,
, ,
, RelativeSource Mode
.
.
, # XAML- Button
NullExtension, StaticExtension Binding:
System.Windows.Controls.Button b = new System.Windows.Controls.Button();
// Background:
b.Background = null;
// Height:
b.Height = System.Windows.SystemParameters.IconHeight;
// Content:
System.Windows.Data.Binding binding = new System.Windows.Data.Binding();
binding.Path = new System.Windows.PropertyPath("Height");
binding.RelativeSource = System.Windows.Data.RelativeSource.Self;
b.SetBinding(System.Windows.Controls.Button.ContentProperty, binding);
, XAML,
,
58
2. XAML
( ProvideValue).
,
(,
, Member StaticExten
sion). ,
!
XAML-, XML-,
. ,
(
, XAML ).
:
, ,
.
Content
WPF (
), XML-.
XAML- .
Visual Basic ( ).
Content Button (
),
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Content="OK"/>
:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
OK
</Button>
Button,
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button.Content>
<Rectangle Height="40" Width="40" Fill="Black"/>
</Button.Content>
</Button>
:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Rectangle Height="40" Width="40" Fill="Black"/>
</Button>
59
, Content;
, ComboBox, ListBox TabControl ( System.
Windows.Controls) Items.
XAML ,
: .
, Sys
tem.Collections.IList, System.Collections.ArrayList
, WPF. XAML-
ListBox, Items ItemsCollec
tion, IList:
<ListBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<ListBox.Items>
<ListBoxItem Content="Item 1"/>
<ListBoxItem Content="Item 2"/>
</ListBox.Items>
</ListBox>
XAML- #:
System.Windows.Controls.ListBox listbox = new System.Windows.Controls.ListBox();
System.Windows.Controls.ListBoxItem item1 =
new System.Windows.Controls.ListBoxItem();
System.Windows.Controls.ListBoxItem item2 =
new System.Windows.Controls.ListBoxItem();
item1.Content = "Item 1";
item2.Content = "Item 2";
listbox.Items.Add(item1);
listbox.Items.Add(item2);
, Items ListBox
.
null (, Items
ListBox, ),
XAML,
. WPF
, OtherList
Box:
60
2. XAML
<OtherListBox>
<OtherListBox.Items>
<ItemCollection>
<ListBoxItem Content="Item 1"/>
<ListBoxItem Content="Item 2"/>
</ItemCollection>
</OtherListBox.Items>
</OtherListBox>
System.Windows.ResourceDictionary WPF ,
12 .
System.Collections.IDictionary, , ,
/ , -
. XAML , IDictionary,
/. , XAML-
ResourceDictionary Color:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Color x:Key="1" A="255" R="255" G="255" B="255"/>
<Color x:Key="2" A="0" R="0" G="0" B="0"/>
</ResourceDictionary>
XAML ey (
XML),
Color . (
Color Key .) , XAML-
#:
System.Windows.ResourceDictionary d = new System.Windows.ResourceDictionary();
System.Windows.Media.Color color1 = new System.Windows.Media.Color();
System.Windows.Media.Color color2 = new System.Windows.Media.Color();
color1.A = 255; color1.R = 255; color1.G = 255; color1.B = 255;
color2.A = 0; color2.R = 0; color2.G = 0; color2.B = 0;
d.Add("1", color1);
d.Add("2", color2);
, XAML2009
WPF XAML IList IDictio
nary, XAML2009 (
XAML2009) .
IList IDictionary, ICollection<T> IDictionary<K,V>,
Add GetEnumerator.
61
, , XAML x:Key,
,
XAML2009 (.
XAML2009).
.
,
SolidColorBrush XAML:
<SolidColorBrush>White</SolidColorBrush>
:
<SolidColorBrush Color="White"/>
, Color .
,
, , "White" ( "white",
"#FFFFFF") SolidColorBrush.
XAML, : , XAML
- , ,
.NET. ,
, XAML ,
,
. , , System.Windows.Media.Brush
SolidColorBrush, GradientBrush
, XAML :
<Brush>White</Brush>
Brush , SolidColorBrush.
,
XAML , ,
XAML.
XAML
XAML .NET,
.NET ( COM-
COM), .
, .
62
2. XAML
. ,
, ,
XAML ( XAML2009).
WPF ,
XAML ( .NET ).
WPF XmlnsDefinitionAttribute,
.NET XML
XAML-. ,
XAML , , ?
, XML. ,
#, .NET mscorlib.dll:
System.Collections.Hashtable h = new System.Collections.Hashtable();
h.Add("key1", 7);
h.Add("key2", 23);
XAML:
<collections:Hashtable
xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<sys:Int32 x:Key="key1">7</sys:Int32>
<sys:Int32 x:Key="key2">23</sys:Int32>
</collections:Hashtable>
clr-namespace .NET
XAML.
, ,
XAML-. (
mscorlib), ,
System.Reflection.Assembly.Load (, ),
, /
.
,
.NET, .NET Framework:
- Hashtable
XAML x:key, Hashtable,
.NET Framework, IDictio
nary 1.0.
System.Int32 ,
, .
, , XAML,
System.ComponentModel.TypeConverter,
.NET Framework 1.0.
, Windows Forms (,
, Visual Studio ,
).
XAML
63
XAML
.
XAML
:
1. IList, IList.Add
.
2. , IDictionary, IDictionary.Add
,
x:Key, . (, XAML2009
IDictionary IList
, .)
3. , (
System.Windows.Markup.ContentPropertyAttribute)
, .
4. ,
, (
),
,
.
5. ,
.
1 2 ,
, 3 , Content,
4 , ,
.
XAML
WPF- .NET-
. WPF-
XAML
(. 13), (. ) ,
, XAML, .
WPF- XAML
.
XAML .
XAML
WPF XAML, .
System.Windows.Markup:
XamlReader XamlWriter. API . XamlReader
Load, Xaml
64
2. XAML
Writer Save. ,
, .NET- ,
XAML . .NET Fra
mework 4 XAML,
. ,
, XAML,
.
XamlReader
XamlReader.Load XAML-,
.NET ,
. , XAML- MyWindow.xaml
Window (
7 ),
Window
:
Window window = null;
using (FileStream fs =
new FileStream("MyWindow.xaml", FileMode.Open, FileAccess.Read))
{
// . , Window
window = (Window)XamlReader.Load(fs);
}
Load FileStream (
System.IO). Load ,
XAML-,
. FileStream using.
XamlReader Stream
( System.Xml.XmlReader),
XAML- .
,
,
. ,
Window StackPanel,
OK:
Window window = null;
using (FileStream fs =
new FileStream("MyWindow.xaml", FileMode.Open, FileAccess.Read))
{
// . , Window
window = (Window)XamlReader.Load(fs);
}
// OK, (
// !)
StackPanel panel = (StackPanel)window.Content;
Button okButton = (Button)panel.Children[4];
XAML
65
Button, , :
(, ,
XAML),
- , XAML,
.
,
, XAML
.
XAML Button,
"OK",
. ,
, ?
, XAML ,
.
XamlReader LoadAsync,
XAML- .
, ,
, XAML- .
, CancelAsync
LoadCompleted, .
LoadAsync .
, Dispatcher.BeginIn
voke (WPF 200 ).
,
XAML x:SynchronousMode="Async". LoadSync
XAML , .
XAML
XAML Name,
. OK, ,
, - Window, Name
:
<Button x:Name="okButton">OK</Button>
#
Window.FindName,
:
Window window = null;
using (FileStream fs =
66
2. XAML
new FileStream("MyWindow.xaml", FileMode.Open, FileAccess.Read))
{
// . , Window
window = (Window)XamlReader.Load(fs);
}
// OK,
Button okButton = (Button)window.FindName("okButton");
x:Name
x:Name ,
,
( System.Windows.Markup.
RuntimeNamePropertyAttribute). , FrameworkElement Framework
ContentElement Name, Runtime
NameProperty("Name"). ,
Name, x:Name.
, . , Name .
WPF
Binding :
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Label Target="{Binding ElementName=box}" Content="Enter _text:"/>
<TextBox Name="box"/>
</StackPanel>
XAML
67
, System.Windows.Markup.Na
meReferenceConverter ( ), , :
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Label Target="box" Content="Enter _text:"/>
<TextBox Name="box"/>
</StackPanel>
XAML
XAML
.NET- ,
XAML. WPF-
XAML, MSBuild Visual Studio.
XAML : XAML-
,
,
XAML . # Visual Basic
XAML .
XAML-
, WPF, Visual Studio,
(Build Action) Page (). (7 ,
.)
, XAML-
, XAML. Class,
XAML. :
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MyNamespace.MyWindow">
...
</Window>
XAML- .NET-
XAML- .NET-
:
CodeDom MSBiuld.
, ( ) .
68
2. XAML
( )
:
namespace MyNamespace
{
partial class MyWindow : Window
{
public MyWindow()
{
// , XAML-!
InitializeComponent();
...
}
...
}
}
XAML- (
MyWindow2), ,
(MyWindow). ,
.
WPF- # Visual Basic Visual Studio
Add New Item ( ),
- WPF-, Visual Studio
XAML- x:Class
, ,
,
.
MSBuild ,
, ,
#
, .
:
XAML
69
<ItemGroup>
<Page Include="MyWindow.xaml"/>
</ItemGroup>
<ItemGroup>
<Compile Include="MyWindow.xaml.cs">
<DependentUpon>MyWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
MyWindow.xaml, :
BAML- (MyWindow.baml),
.
#- (MyWindow.g.cs),
, .
BAML
BAML Binary Application Markup Lan
guage ( ). XAML,
, .
XAML
, XAML BAML
. BAML MSIL;
,
, XAML- ( ).
, BAML XAML.
. WPF4
BAML- (.
XAML).
70
2. XAML
- CAML
WPF XAML
BAML MSIL. MSIL- CAML,
Compiled Application Markup Language (
). ,
(BAML) (CAML).
WPF
, . BAML
, :
, MSIL, ( ) .
, CAML BAML, .
, . ,
DLL-,
..
XAML -
( x:Class), ,
,
XAML- .
.g.cs ( .g.vb), g (generated).
, x:Class .
( internal)
XAML-, .
InitializeComponent,
BAML-,
, XAML-,
( XAML).
, ,
,
( BAML ),
BAML
. ,
, ,
, .
InitializeComponent .
XAML
InitializeComponent
!
, ,
XAML- ( BAML-
), , ,
null.
XAML
XAML
, ( ASP.NET).
Code XAML:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MyNamespace.MyWindow">
<Button Click="button_Click">OK</Button>
<x:Code><![CDATA[
void button_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
]]></x:Code>
</Window>
XAML- x:Code
, .g.cs-. ,
XAML- ; ,
.
<![CDATA[...]]> , '<' <, &,
CDATA XML, XML-. (,
]]>, CDATA!)
, XAML- . ,
, Visual Studio , IntelliSense
.
71
72
2. XAML
FAQ
BAML XAML?
, , BAML
XAML ,
.
,
XAML. , System.Windows.
Application.LoadComponent, BAML:
System.Uri uri = new System.Uri("/WpfApplication1;component/MyWindow.xaml",
System.UriKind.Relative);
Window window = (Window)Application.LoadComponent(uri);
, BAML, .xaml .
, XAML-
FileStream, LoadComponent
(URI)
. LoadComponent
BAML-, ,
URI ( , MSBuild,
XAML-).
Visual Studio InitializeComponent Applica
tion.LoadComponent BAML-, ,
. 12
URI.
, System.Windows.Mark
up.XamlWriter, XAML- (
, ). XamlWriter
Save;
XAML- :
string xaml = XamlWriter.Save(window);
, BAML- , ,
,
. (,
HTML-, JavaScript- CSS- .)
.NET Reflector BamlViewer
(. http://codeplex.com/reflectoraddins), BAML-,
, XAML-.
XAML2009
XAML ,
WPF, XAML WPF
WPF.
XAML2009
73
XAML2006
x:TypeArguments,
.
x:TypeArguments ,
XAML2006
.
, ,
. XAML
. :
74
2. XAML
C#:
public class PhotoCollection : ObservableCollection<Photo> {}
XAML:
<custom:PhotoCollection>
<custom:Photo .../>
<custom:Photo .../>
</custom:PhotoCollection>
XAML2009 x:TypeArguments ,
, , ObservableCollection<Photo>
XAML:
<collections:ObservableCollection TypeArguments="custom:Photo">
<custom:Photo .../>
<custom:Photo .../>
</collections:ObservableCollection>
, collections
System.Collections.ObjectModel, ObservableCollection.
XAML2009
x:Key,
, . :
<collections:Dictionary x:TypeArguments="x:Int32, x:String">
<x:String x:Key="1">One</x:String>
<x:String x:Key="2">Two</x:String>
</collections:Dictionary>
, collections
System.Collections.Generic.
XamlObjectWriter XAML2009
. XamlObjectWriterSettings.PreferUnconvertedDictionaryKeys.
true, System.Xaml ,
IDictionary, , :
System.Xaml IDictionary.Add
,
.NET Framework, System.Xaml
, .
XAML2009
75
XAML2006 .NET, String
Int32, ,
System mscorlib; , :
<sys:Int32 xmlns:sys="clr-namespace:System;assembly=mscorlib">7</sys:Int32>
XAML2009 XAML 13
.NET. ,
x, : x:Byte, x:Boolean, x:Int16,
x:Int32, x:Int64, x:Single, x:Double, x:Decimal, x:Char, x:String, x:Object, x:Uri, x:Ti
meSpan. , :
<x:Int32 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">7</x:Int32>
XAML-, XAML,
:
<x:Int32>7</x:Int32>
XAML2009 x:Arguments,
.
, , System.Version,
. XAML2006
,
( , ,
, 0.0).
XAML2009 ,
:
<sys:Version x:Arguments="4.0.30319.1"/>
;
.
x:TypeArguments, x:Arguments
. , x:Arguments.
, System.Version,
, :
<sys:Version>
<x:Arguments>
<x:Int32>4</x:Int32>
<x:Int32>0</x:Int32>
<x:Int32>30319</x:Int32>
<x:Int32>1</x:Int32>
</x:Arguments>
</sys:Version>
76
2. XAML
x:FactoryMethod XAML2009
, . x:Fac
toryMethod ,
. , XAML-
Guid, Guid.
NewGuid:
<Label xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:Guid x:FactoryMethod="sys:Guid.NewGuid"/>
</Label>
x:FactoryMethod x:Arguments,
, .
, Marshal.GetExcep
tionForHR, HRESULT
.NET, CLR
:
<Label xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:interop=
"clr-namespace:System.Runtime.InteropServices;assembly=mscorlib">
<sys:Exception x:FactoryMethod="interop:Marshal.GetExceptionForHR">
<x:Arguments>
<x:Int32>0x80004001</x:Int32>
</x:Arguments>
</sys:Exception>
</Label>
.2.3 , XAMLPAD2009
Label StackPanel.
XAML2006
XAML-. XAML2009 ,
. , XAML2009
,
:
<Button Click="{custom:DelegateFinder Click}"/>
,
.
XAML
77
.2.3. ,
XAML
.
XAML2009 x:Members x:Property,
XAML. WPF.
XAML Windows Workflow Foundation,
:
<Activity x:Class="ActivityLibrary1.Activity1" ...>
<x:Members>
<x:Property Name="argument1" Type="InArgument(x:Int32)"/>
<x:Property Name="argument2" Type="OutArgument(x:String)"/>
</x:Members>
...
</Activity>
XAML
, XAML- Xaml
Reader.Load XamlWriter.Save System.Windows.Markup.
API WPF
WPF ,
XAML2006.
78
2. XAML
System.Xaml System.Xaml.
XamlReader System.Xaml.XamlWriter (
/), XAML.
System.Xaml ,
, .
XAML2009.
XamlReader XAML
(
), XamlWriter
.
:
( System.Xaml.XamlReader):
System.Xaml.XamlXmlReader XML- ( System.Xml.XmlReader, System.
IO.TextReader, System.IO.Stream ,
).
System.Xaml.XamlObjectReader .
System.Win
dows.Baml2006.Baml2006Reader BAML- ( WPF
2006).
System.Xaml.XamlBackgroundReader XamlReader,
,
, .
( System.Xaml.XamlWriter):
System.Xaml.XamlXmlWriter XML ( System.Xml.XmlWriter,
System.IO.TextWriter Stream).
System.Xaml.XamlObjectWriter .
XAML ,
.NET Framework,
System.IO System.Xml.
,
, XAML .
.2.4, ,
.NET Framework. XAML
XML,
, .
, .2.4 , ,
, .
XAML (
79
XAML
API). 40
(Autodesk 3ds Max Maya, AutoCAD DXF, NewTek LightWave ..), Adobe
Illustrator/Photoshop/Flash/Fireworks, SVG, HTML 5 Canvas, Visio, PowerPo
int, Windows Metafile (WMF), Enhanced Metafile (EMF), Visual
Basic 6!
XML
XAML
XML
BAML
.2.4. ,
XAML, WPF!
XAML. , ,
. XamlObjectReader
WPF, WPF XAML
- System.Windows.Markup.XamlWriter.
XAML WPF, .
80
2. XAML
FAQ
XAML-
XamlXmlReader, XmlReader? XAML
XML?
XamlXmlReader XmlReader,
.
XML,
XAML.
XAML, XAML
,
XML.
,
XAML. , XAML-
Button, Content
"":
<!-- : -->
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
OK
</Button>
<-- : -->
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button.Content>
OK
</Button.Content>
</Button>
<!-- : -->
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Content="OK"/>
XmlReader -, XamlXmlReader
. ,
XAML (
XAML),
. , XamlXmlReader
, ,
Button
Content.
, ,
XAML, XamlXmlReader (
XAML),
, . ,
XamlXmlReader , Content
System.Object.
XAML
81
XAML ,
. XamlReader XamlWriter ,
,
,
. , reader
XAML, writer , :
//
while (reader.Read())
{
writer.WriteNode(reader);
}
,
. , XAMLPAD2009
XAML XML ( )
,
(, ). 2.1
,
XamlXmlReader, XamlObjectWriter.
XamlXmlReader XML.
, System.IO.StringReader
XamlXmlReader ( , StringReader
TextReader).
2.1. XAML-,
XML,
public static object ConvertXmlStringToObjectGraph(string xmlString)
{
// String -> TextReader -> XamlXmlReader
using (TextReader textReader = new StringReader(xmlString))
using (XamlXmlReader reader = new XamlXmlReader(textReader,
System.Windows.Markup.XamlReader.GetWpfSchemaContext()))
using (XamlObjectWriter writer = new XamlObjectWriter(reader.SchemaContext))
{
//
while (reader.Read())
{
writer.WriteNode(reader);
}
// XamlObjectWriter
//
return writer.Result;
}
}
82
2. XAML
XamlObjectWriter WPF-,
XAML WPF.
, XAML- .
XAML
XAML
XAML,
, - ,
.
XamlReader,
, NodeType,
:
StartObject
, XML-
, .
GetObject ,
, XAML ,
( ListBox,
).
EndObject (
StartObject GetObject). StartObject
GetObject EndObject, .
StartMember
: ( ), (
) XAML, x:Key.
, StartMember
StartObject GetObject. , XML
,
, , .
EndMember (
StartMember). StartMember
EndMember.
Value .
- ,
Value StartMember (
StartObject GetObject).
NamespaceDeclaration
XML (
). , Start
Object, .
, , ,
, ,
.
XAML
83
None -,
, .
.
XamlReader ,
: Type, Member, Value Namespace.
. , NodeType StartObject, Type
XamlType, null.
NodeType StartMember, Member Xaml
Member, null. NodeType Value,
Value null. NodeType NamespaceDeclaration,
Namespace.
, XAML .NET Framework 4.0 (
XamlObjectReader) IXamlLineInfo,
, . HasLineInfo
true, ,
LineNumber LinePosition .
FAQ
XamlType XamlMember,
XAML?
XAML
.NET.
XamlType System.Type (
UnderlyingType), XAML ,
, .
XamlType .NET.
XamlMember System.Reflection.MemberInfo (
UnderlyingMember, MemberInfo
). XAML ,
IsDirective PreferredXamlNamespace.
,
XAML, .2.1 , XamlXmlReader
XAML- 2.2. XamlNodeType
, .
2.2. XAML-
XamlXmlReader
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- -->
<Button Name="okButton" Click="okButton_Click">OK</Button>
84
2. XAML
<Button x:Name="cancelButton">Cancel</Button>
<ListBox>
<-- -->
<ListBoxItem Content="Item 1"/>
<ListBoxItem>Item 2</ListBoxItem>
<ListBoxItem>
<ListBoxItem.Content>
Item 3
</ListBoxItem.Content>
</ListBoxItem>
</ListBox>
</StackPanel>
NamespaceDeclaration
Namespace=".../xaml/presentation",
Prefix=""
13
NamespaceDeclaration
Namespace=".../xaml", Prefix="x"
13
StartObject
Type=StackPanel
StartMember
Member= UIElementCol
lection
GetObject
null
StartMember
Member=_Items, XamlDirective
List<Object>
StartObject
Type=Button
StartMember
Member=Name String
11
Value
Value="okButton"
11
EndMember
null
11
StartMember
Member=Click RoutedEventHander 4
(IsEvent=true)
27
Value
Value="okButton_Click"
27
EndMember
null
27
StartMember
Member=Content Object
54
Value
Value="OK"
54
EndMember
null
54
EndObject
null
54
StartObject
Type=Button
StartMember
Member=Name, XamlDirective
String
11
85
XAML
XamlNodeType
Value
Value="cancelButton"
11
EndMember
null
11
StartMember
Member=Content Object
41
Value
Value="Cancel"
41
EndMember
null
41
EndObject
null
41
StartObject
Type=ListBox
StartMember
Member=Items ItemCollection
GetObject
null
StartMember
Member=_Items, XamlDirective
List<Object>
StartObject
Type=ListBoxItem
18
Value
Value="Item 1"
18
EndMember
null
18
EndObject
null
StartObject
Type=ListBoxItem
26
Value
Value="Item 2"
26
EndMember
null
26
EndObject
null
26
StartObject
Type=ListBoxItem
10
11
Value
Value="Item 3"
13
EndMember
null
13
EndObject
null
14
EndMember
null
15
EndObject
null
15
EndMember
null
15
EndObject
null
15
EndMember
null
16
EndObject
null
16
EndMember
null
16
EndObject
null
16
86
2. XAML
, ListBoxItem .2.1
, Button,
Name Button XAML
x:Name. ( XamlMember XamlDirective,
IsDirective true.)
, GetObject, EndMember EndObject
;
. -
XAML
, / .
(http://schemas.openxmlformats.org/
markup-compatibility/2006, mc)
Ignorable, XAML
/ ,
.NET. (
ProcessContent, Ignorable
.)
Expression Blend
XAML- ,
. . :
<StackPanel xmlns="http://schemas.microsoft.com/client/2007"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="100" d:DesignHeight="100">
...
</StackPanel>
mc:Ignorable ,
, mc:ProcessContent ,
.
XamlXmlReader ,
, .
, .
.
XAMLPAD2009 XAML ,
. XAML-,
WPF
XAML. , .
XAML
87
, ,
, XamlObjectWriter , ,
: Failed to create a 'Click' from the text 'button_Click'.
, XamlObjectWriter RootObjectInstance,
,
XAML . ,
x:Class, XAML-
.
Window Page. 7
, , Window
, XAMLPAD2009
.
(, , Window,
), XAML
.
2.3 ,
XAML-
.
2.3. XAML-
public static object ConvertXmlStringToMorphedObjectGraph(string xmlString)
{
// String -> TextReader -> XamlXmlReader
using (TextReader textReader = new StringReader(xmlString))
using (XamlXmlReader reader = new XamlXmlReader(textReader,
System.Windows.Markup.XamlReader.GetWpfSchemaContext()))
using (XamlObjectWriter writer = new XamlObjectWriter(reader.SchemaContext))
{
//
while (reader.Read())
{
// x:Class
if (reader.NodeType == XamlNodeType.StartMember &&
reader.Member.IsEvent || reader.Member == XamlLanguage.Class)
{
reader.Skip();
}
if (reader.NodeType == XamlNodeType.StartObject &&
reader.Type.UnderlyingType == typeof(Window))
{
// Window Page
writer.WriteStartObject(new XamlType(typeof(Page),
reader.SchemaContext));
}
88
2. XAML
else
{
//
writer.WriteNode(reader);
}
}
// XamlObjectWriter
//
return writer.Result;
}
}
XML
WPF- XAML- XML
. XamlObjectReader
WPF-, 2.4 , XML
, XamlObjectReader XamlObject
Writer. XAML,
XML-,
.
XAML
89
. XamlXmlReader ,
, XamlXmlWriter System.IO.StringWriter. (Xml
Writer StringBuilder.)
XmlWriter (
), XML-
(<?xml version="1.0" encoding="utf-16"?>).
,
XamlXmlWriter StringWriter (
TextWriter), XmlWriter.
// TextWriter -> XamlXmlWriter
using (StringWriter textWriter = new StringWriter())
using (XamlXmlWriter writer = new XamlXmlWriter(textWriter,
reader.SchemaContext))
{
...
}
XamlServices
,
XAML
, System.Xaml.Xaml
Services, :
Load ,
, Stream, TextReader, XmlReader XamlReader.
90
2. XAML
,
XamlReader.Load. Load
XamlXmlReader XamlObjectWriter, 2.1.
Parse Load, Parse ,
XAML- .
StringReader, XmlReader XamlXmlReader,
Load. , Parse
ConvertXmlStringToObjectGraph,
2.1.
Save ,
, , Stream, TextWri
ter, XmlWriter XamlWriter
. Save XamlObjectReader
XamlXmlWriter ( XamlWriter).
Indent OmitXmlDeclaration XamlWriter
true, 2.4.
Transform ,
, .
XamlServices.Transform ,
.
,
(IXamlLineInfo
IXamlLineInfoConsumer ). , Transform
:
public static void Transform(XamlReader reader, XamlWriter writer)
{
IXamlLineInfo producer = reader as IXamlLineInfo;
IXamlLineInfoConsumer consumer = writer as IXamlLineInfoConsumer;
bool transferLineInfo = (producer != null && producer.HasLineInfo &&
consumer != null && consumer.ShouldProvideLineInfo);
//
while (reader.Read())
{
//
if (transferLineInfo && producer.LineNumber > 0)
consumer.SetLineInfo(producer.LineNumber, producer.LinePosition);
writer.WriteNode(reader);
}
}
, 2.1
( ), XamlServices.Transform,
2.5. , ConvertXmlStringToObjectGraph
, XamlServices.Parse.
XAML
2.5. 2.1
public static object ConvertXmlStringToObjectGraph(string xmlString)
{
// String -> TextReader -> XamlXmlReader
using (TextReader textReader = new StringReader(xmlString))
using (XamlXmlReader reader = new XamlXmlReader(textReader,
System.Windows.Markup.XamlReader.GetWpfSchemaContext()))
using (XamlObjectWriter writer = new XamlObjectWriter(reader.SchemaContext))
{
//
XamlServices.Transform(reader, writer);
// XamlObjectWriter
//
return writer.Result;
}
}
XamlServices WPF XAML!
, , XamlServices.Parse XamlServices.Save
XAML 2.4
, :
public static string RewriteXaml(string xmlString)
{
return XamlServices.Save(XamlServices.Parse(xmlString));
}
,
XamlXmlReader, XamlObjectWriter (
XamlServices.Parse),
XamlObjectReader
XmlWriter XamlXmlWriter.
.
XAML,
x:Class.
, , XamlObject
Writer WPF-.
XamlReader XamlWriter:
return System.Windows.Markup.XamlWriter.Save(
System.Windows.Markup.XamlReader.Parse(xmlString));
, :
using (StringWriter textWriter = new StringWriter())
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter,
91
92
2. XAML
,
XAML- .
XAML
XAML (http://schemas.microsoft.com/winfx/2006/xaml)
,
XAML.
,
, .
(Key, Name, Class, Subclass Code), .2.2 .
x,
XAML .
, W3C
XAML
, XML
World Wide Web Consortium (W3C): xml:space
xml:lang .
xml XML http://www.
w3.org/XML/1998/namespace.
93
XAML
2.2. XAML
x
x:AsyncRecords
2006+
XAML
X:Arguments
2009
(
,
),
.
x:FactoryMethod
()
X:Boolean
2009
System.
Boolean
X:Byte
2009
System.
Byte
x:Char
2009
System.
Char
x:Class
2006+
x:ClassAttributes 2009
,
x:Class
,
.
.NET
WPF;
,
Windows Workflow Foun
dation
x:ClassModifier
2006+
,
x:Class
,
x:Class (
).
(
public internal #)
x:Code
2006+
XAML,
x:Class
,
,
x:Class.
x:ConnectionId
2006+
x:Decimal
2009
System.Decimal
x:Double
2009
System.Double
94
2. XAML
2.2 ()
x:FactoryMethod
2009
x:FieldModifier
2006+
,
x:Name (
)
,
( internal).
x:ClassModifier,
(,
public, private, #)
x:Int16
2009
System.Int16
x:Int32
2009
System.Int32
x:Int64
2009
System.Int64
x:Key
, 2006+
IDictionary
x:Members
WPF 2009
XAML
,
x:Class
x:Name
2006+
,
x:Class
,
,
x:Object
System.Object
x:Property
WPF 2009
XAML
x:Members
x:Shared
2006+
ResourceDictionary,
XAML
false
(.
12)
x:Single
2009
System.Single
x:String
2009
System.String
x:Subclass
2006+
,
x:Class
2009
,
x:Class,
,
XAML.
95
XAML
.NET (
,
)
x:SynchronousMode 2006+
,
XAML
x:TimeSpan
2009
System.TimeSpan
x:TypeArguments
XAML2009
,
XAML2006
,
x:Class
2006+
( List<T>),
(, List<Int32>
List<String>).
.
,
,
XML
x:Uid
2006+
(.
12)
x:Uri
System.Uri
x:XData
, 2006+
IXml
Serializable
2009
XML,
XAML (. 13)
.2.3 XAML,
,
( .NET System.Windows.
Markup). Extension ,
.
2.3. XAML
, x
x:Array
.NET. x:Array
. x:Type,
x:Null
null
96
2. XAML
2.3 ()
x:Reference
.
,
x:Static
, ,
, .
XAML ,
. Member
XML,
x:Type
System.Type , typeof
#. TypeName
XML,
, XAML WPF,
XAML # . ,
,
.
, ,
! ( , ,
Parse, ,
.)
, ,
XAML (, null
), ,
.
XAML ,
.
WPF , , ,
API WPF ,
XAML. , WPF
(
, ), WPF-
, , , Win
dows Forms. XAML ,
,
WPF ,
XAML (, ),
(, ,
).
97
,
WPF , XAML, ,
XML .
.
1: XML ,
. XML-,
. , IntelliSense ,
! XML
(, XAML
),
.
, WPF
, 3D- .. XAML
. XAML
-
,
,
. , XAML API
WPF ,
.
HTML .
2: , XML,
XML ,
. WPF-
,
?
WPF XML BAML,
. BAML ,
XAML, . ,
XML
, , XML .
3.
WPF
I
, WPF,
.NET . -
WPF ,
. ,
WPF.
(, ),
(, ).
About
().
, WPF,
,
. WPF
, , . .3.1
12 .
Object , .NET,
,
WPF.
DispatcherObject , ,
, .
WPF DispatcherObject , ,
. Dispatcher
99
WPF
Win32, 7.
DependencyObject , ,
;
.
Freezable ,
, ,
.
, , Dis
patcherObject. ,
, .
Freezable : ,
, .
Visual ,
. 15
.
UIElement
, ,
. 5
6 : , ,
.
Visual3D ,
. 16 .
UIElement3D
, .
16.
Object
DispatcherObject
DependencyObject
Freezable
Visual
Visual3D
UIElement
UIElement3D
FrameworkElement
ContentElement
FrameworkContentElement
Control
2D
3D
.3.1. , WPF
Documents
100
3. WPF
ContentElement , UIElement,
,
.
ContentElement , ,
Visual. Content
Element Visual (
, ).
FrameworkElement , ,
, ,
Windows,
.
FrameworkContentElement FrameworkElement .
11 ,
.
Control
, Button, ListBox StatusBar. Control
FrameworkElement , Foreground, Back
ground FontSize, .
WPF III.
, UIElement FrameworkElement, Content
Element FrameworkContentElement. UIElement FrameworkElement
ContentElement FrameworkContentElement ,
WPF UIElement ContentElement.
XAML
. WPF
,
.
3.1
About (),
Window. Window StackPanel (. 5),
StackPanel, Button.
3.1. About XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="About WPF 4 Unleashed" SizeToContent="WidthAndHeight"
Background="OrangeRed">
<StackPanel>
<Label FontWeight="Bold" FontSize="20" Foreground="White">
WPF 4 Unleashed
</Label>
101
<Label> 2010 SAMS Publishing</Label>
<Label>Installed Chapters:</Label>
<ListBox>
<ListBoxItem>Chapter 1</ListBoxItem>
<ListBoxItem>Chapter 2</ListBoxItem>
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button MinWidth="75" Margin="10">Help</Button>
<Button MinWidth="75" Margin="10">OK</Button>
</StackPanel>
<StatusBar>You have successfully registered this product.</StatusBar>
</StackPanel>
</Window>
.3.2 , (
, 3.1 XAMLPAD2009,
), .3.3 .
.3.2. , 3.1
Window
StackPanel
Label
Label
Label
String
String
String
ListBox
StackPanel
ListBoxItem
ListBoxItem
Button
Button
String
String
String
String
.3.3. , 3.1
StatusBar
String
102
3. WPF
, WPF-,
XAML. 3.1
, .
,
? , WPF (,
, ..) .
,
,
, .
, 6.
WPF ,
. ,
,
.
, ,
. ,
,
. , ListBox ,
WPF-: Border, ScrollBar .
,
, System.Windows.Media.Visual System.Win
dows.Media.Visual3D. ( ,
3.1) ,
.
XAML, XamlPadX,
,
( ) , XAML-.
. 3.4 ,
3.1 Windows 7 Aero.
,
, ScrollBar
ListBox Border Label. , Button, La
bel ListBoxItem
Button Border ButtonChrome. (
,
, .
, Button Margin
10, Label 0.)
Border
ContentPresenter
TextBlock
Border
ContentPresenter
TextBlock
TextBlock
TextBlock
ScrollBar
ContentPresenter
ContentPresenter
Grid
ScrollBar
ButtonChrome
ButtonChrome
ListBoxItem
Border
ContentPresenter
TextBlock
ListBoxItem
Border
ContentPresenter
TextBlock
VirtualizingStackPanel
AdornerLayer
ScrollContentPresenter
Border
ScrollViewer
StackPanel
Button
ListBox
AdornerLayer
Button
ItemsPresenter
Rectangle
TextBlock
ContentPresenter
Border
Label
AdornerLayer
.3.4. 3.1;
Label
Label
StackPanel
ContentPresenter
AdornerDecorator
Border
Window
TextBlock
ContentPresenter
Border
StatusBarItem
DockPanel
ItemsPresenter
Border
StatusBar
103
104
3. WPF
WPF-,
. ,
WPF,
,
(. 14 , ,
) (. 15).
, ,
Button,
WPF . -
, , 14,
- .
,
( , , ),
,
Windows!
System.Windows.LogicalTreeHelper System.Windows.Media.
VisualTreeHelper. 3.2 3.1,
About
. ( ,
3.1 x:Class="AboutDialog" xmlns:x.)
3.2.
using
using
using
using
System;
System.Diagnostics;
System.Windows;
System.Windows.Media;
105
depth, 0,
Window obj,
, .3.2 3.3.
,
Window. Print
VisualTree OnContentRendered,
.
, .3.4,
,
, .
, (?)
. , , Window
Border, AdornerDecorator, AdornerLayer, ContentPresenter
. StackPanel . 3.4
ContentPresenter, Visual
TreeHelper .
106
3. WPF
. , Visual
(VisualParent, VisualChildrenCount GetVisualChild)
. FrameworkElement,
, Button Label,
FrameworkContentElement Parent,
, LogicalChildren,
.
,
, Children.
, Button Label, Content
.
WPF ;
, ,
, . ,
, ,
.NET, , ,
. , ,
, , , .
,
.
, , ,
, .. ,
.
.
WPF
. , Button 111 (
98 Control )!
XAML- (
) . ,
,
.
107
, ,
,
.NET :
.
WPF , .
,
. WPF, ,
!
.NET,
, WPF.
WPF API; .NET-
( XAML)
.
3.3 , Button
IsDefault.
3.3.
public class Button : ButtonBase
{
//
public static readonly DependencyProperty IsDefaultProperty;
static Button()
{
//
Button.IsDefaultProperty = DependencyProperty.Register("IsDefault",
typeof(bool), typeof(Button),
new FrameworkPropertyMetadata(false,
new PropertyChangedCallback(OnIsDefaultChanged)));
...
}
// .NET ()
public bool IsDefault
{
get { return (bool)GetValue(Button.IsDefaultProperty); }
set { SetValue(Button.IsDefaultProperty, value); }
}
108
3. WPF
// , ()
private static void OnIsDefaultChanged(
DependencyObject o, DependencyPropertyChangedEventArgs e) { ... }
...
}
IsDefaultProperty System.Windows.DependencyProperty
.
DependencyProperty , ,
Property.
, ,
XAML .
DependencyPro
perty.Register (IsDefault), (bool)
, (Button). (
Register) ,
, WPF ,
,
. Button Register
;
false ,
.
IsDefault.
GetValue SetValue, System.Windows.DependencyObject,
,
. GetValue , Set
Value, , SetValue ,
, . .NET IsDefault
( )
; Button
GetValue SetValue, .
.NET
, ,
XAML. WPF
GetValue SetValue.
, ,
.NET .
109
.NET
XAML!
XAML , , WPF GetValue Set
Value!
XAML
- GetValue/SetValue. ,
. WPF
, , .
3.3
.
GetValue SetValue
, IsDefaultProperty (
),
, ,
.NET. WPF
( .NET),
-
. 111 ,
104 ..! 89 111
Button 82 104 Label
.
.
,
-
,
. ,
( Background
Button), FrameworkPropertyMetadataOptions.
AffectsRender DependencyProperty.
Register. ,
, .
WPF
.
, ,
.
,
110
3. WPF
.
, , ,
About 3.1
.
MouseEnter MouseLeave:
<Button MouseEnter="Button_MouseEnter" MouseLeave="Button_MouseLeave"
MinWidth="75" Margin="10">Help</Button>
<Button MouseEnter="Button_MouseEnter" MouseLeave="Button_MouseLeave"
MinWidth="75" Margin="10">OK</Button>
C#
:
// ,
void Button_MouseEnter(object sender, MouseEventArgs e)
{
Button b = sender as Button;
if (b != null) b.Foreground = Brushes.Blue;
}
// ,
void Button_MouseLeave(object sender, MouseEventArgs e)
{
Button b = sender as Button;
if (b != null) b.Foreground = Brushes.Black;
}
XAML. Trigger:
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Blue"/>
</Trigger>
IsMouseOver Button,
true Mouse
Enter false MouseLeave.
, , IsMouseOver
false, . WPF !
,
. , -
, Button.
Style,
14. ,
,
XML-:
111
, WPF.
,
.NET ( );
14.
,
(. 6).
,
17 .
Triggers!
Triggers FrameworkElement TriggerBase (
)
, Button. , ,
, . ( ) .
(
) -
,
. 3.4 ,
3.1, Window
FontSize FontStyle. . 3.5
. (, SizeToContent
Window !)
112
3. WPF
. Button List
BoxItem, .
FontSize Label ,
FontSize 20, 30. ,
113
, . , ,
XML (
XAML),
. ,
, ( Content Children) , Freezable.
,
, XAML
, .
WPF ,
.
,
114
3. WPF
,
. , , .
.3.6 , WPF
.
.
( )
.3.6.
1:
. ,
,
:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
,
(9). (1)
DependencyObject.SetValue,
XAML (
,
Button.IsDefault). (10)
, ;
, .
, 14.
,
FontSize Font
Style StatusBar 3.4. StatusBar
(8). ,
(9),
115
,
StatusBar.
,
, Depen
dencyPropertyHelper.GetValueSource. ValueSource, : BaseValueSource, ( 1) IsExpression, IsAnimated
IsCoerced, 24.
StatusBar 3.1 3.4,
FontSize FontStyle, BaseValueSource DefaultStyle, , . (, , .
DefaultStyleTrigger.)
! WPF
, ,
. ,
WPF-.
, , ,
MouseEnter MouseLeave.
, MouseLeave
, Button .
Foreground (
), , .
WPF
,
. , DependencyObject
: ClearValue. C#
Button b:
b.ClearValue(Button.ForegroundProperty);
(Button.ForegroundProperty DependencyProperty.)
ClearValue WPF ,
.
, IsMouseOver, , . ,
, .
116
3. WPF
2:
, 1, (
, System.Windows.Expression), WPF
.
( 13).
3:
,
( ,
2) . , ( 17)
! WPF .
4:
, WPF
CoerceValueCallback,
.
, .
, WPF ProgressBar
Value
Minimum Maximum, Minimum,
Minimum, Maximum Maximum.
, CoerceValue
WPF .
5:
ValidateValueCallback,
.
true, , false .
false, WPF ,
.
117
,
.
, WPF.
, About FontSize Font
Style Window ( 3.4),
StackPanel,
Button. StackPanel
, StackPanel ,
!
FontSize FontStyle, TextElement. 3.5
XAML,
.
(.3.7).
3.5. About,
StackPanel
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="About WPF 4 Unleashed" SizeToContent="WidthAndHeight"
Background="OrangeRed">
<StackPanel>
<Label FontWeight="Bold" FontSize="20" Foreground="White">
WPF 4 Unleashed
</Label>
<Label> 2010 SAMS Publishing</Label>
<Label>Installed Chapters:</Label>
<ListBox>
<ListBoxItem>Chapter 1</ListBoxItem>
<ListBoxItem>Chapter 2</ListBoxItem>
</ListBox>
118
3. WPF
, , FontStyles.Italic, Orientation.
Horizontal HorizontalAlignment.Center, XAML-
Italic, Horizontal Center. Enum
Converter .NET Framework,
.
XAML- 3.5 FontSize
FontStyle StackPanel , C# ,
, ,
.
,
.NET !
SetFontSize
DependencyObject.SetValue,
, ,
DependencyObject:
119
GetXXX (
XXX ), Dependency
Object.GetValue:
public static double GetFontSize(DependencyObject element)
{
return (double)element.GetValue(TextElement.FontSizeProperty);
}
,
GetXXX SetXXX , GetValue
SetValue .
FontSize FontStyle
3.5 , Button Control,
FontSize FontStyle, , ,
TextElement ( TextBlock,
TextElement)!
, TextElement.FontSizeProperty Control.FontSizeProperty ( TextElement.FontStyleProperty
Control.FontStyleProperty)?
. TextElement
:
TextElement.FontSizeProperty = DependencyProperty.RegisterAttached(
"FontSize", typeof(double), typeof(TextElement),new FrameworkPropertyMetadata(
SystemFonts.MessageFontSize, FrameworkPropertyMetadataOptions.Inherits |
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsMeasure),
new ValidateValueCallback(TextElement.IsValidFontSize));
IsDefault Button , RegisterAttached ,
.
, Control FontSize
! AddOwner TextElement ,
:
120
3. WPF
Control.FontSizeProperty = TextElement.FontSizeProperty.AddOwner(
typeof(Control), new FrameworkPropertyMetadata(SystemFonts.MessageFontSize,
FrameworkPropertyMetadataOptions.Inherits));
FontSize, FontStyle , ,
, TextElement!
, , ( GetXXX SetXXX), ,
, .
, Windows Forms,
WPF Tag ( System.Object), , . , DependencyObject. , ( WPF )!
:
XAML- SetXXX,
DependencyObject.
SetValue . ,
. ,
Button IsTextSearchEnabled,
ItemsControl, :
// Button
// true
okButton.SetValue(ItemsControl.IsTextSearchEnabledProperty, true);
Button , ,
.
. , Tag FrameworkElement , GeometryModel3D (
, 16,
Tag):
GeometryModel3D model = new GeometryModel3D();
model.SetValue(FrameworkElement.TagProperty, "my custom data");
WPF .
121
About
,
. (
WPF.)
Panel ,
.
Panel
, ,
.
,
Panel
. 5 21
.
,
.NET Framework WPF. WPF
.NET API, Windows
Forms, .
-
,
,
.
,
, , :
,
( )! ,
.
,
.
II
II.
WPF-
4 ,
5
6 : , ,
7
8 Windows 7
4.
WPF-
.
( )
, .
WPF .
- .
.
,
, ,
; ,
, .
, ,
, System.Windows.Cont
rols.Panel. , ( ,
), System.Windows.UIElement.
WPF ,
:
4 ,
5
21
, .
,
.4.1 ,
. , ,
126
4. ,
, , .
(
), , .
VerticalAlignment
HorizontalAlignment
Margin
Padding
Height
FlowDirection
Width
LayoutTransform
RenderTransform
.4.1. , ,
WPF ,
-.
, .
, (,
),
. WPF
, ,
, . (
Window, SizeToContent,
.)
.
Height Width
, FrameworkElement, Height (
) Width () ( double), MinHeight, MaxHeight, MinWidth Max
Width,
.
, XAML.
127
,
MinHeight MinWidth,
,
.
MaxHeight MaxWidth ( ,
).
Height Width,
, Min Max.
MinHeight MinWidth 0, MaxHeight MaxWidth Double.Positive
Infinity ( XAML "Infinity").
!
,
ContentControl, Button Label,
,
. ,
. ,
.
"Auto"
Height Width FrameworkElement
Double.NaN (NaN not a number ), ,
.
XAML- "NaN" ( )
"Auto" ( ),
LengthConverter, .
, ,
Double.IsNaN.
, FrameworkElement
, :
DesiredSize ( UIElement)
RenderSize ( UIElement)
ActualHeight ActualWidth
,
,
, . Desi
redSize
128
4. ,
ActualHeight
ActualWidth ( RenderSize)!
RenderSize (, ActualHeight Actu
alWidth) . ,
, .
LayoutUpdated,
UIElement.
UIElement UpdateLayout,
,
. UpdateLayout
, ,
,
.
Margin Padding
Margin Padding .
Margin , FrameworkElement,
Padding ,
Control ( Border). , Margin
, Padding
.
System.Windows.Thickness; ,
, double.
4.1, Label
Padding Margin.
Border, . .4.2
129
, ,
Canvas ( ,
). , Margin ( Padding)
.
(Paddings):
(Margins):
130
4. ,
<!-- 2 :
, - : -->
<Label Margin="20,5" Background="Aqua">20,5</Label>
</Border>
<Border BorderBrush="Black" BorderThickness="1">
<!-- 4 : , , , : -->
<Label Margin="0,10,20,30" Background="Aqua">0,10,20,30</Label>
</Border>
Label Padding 5,
. 4.1
Padding 0.
, (,
Margin, 0),
Padding .
Thickness
, Margin
Padding, , System.Windows.Thick
nessConverter, Thickness .
Thickness :
double, . , C#
:
myLabel.Margin = new Thickness(10);
// , Margin="10" XAML
myLabel.Margin = new Thickness(20,5,20,5); // , Margin="20,5" XAML
myLabel.Margin = new Thickness(0,10,20,30); // , Margin="0,10,20,30" XAML
,
!
FAQ
WPF?
LengthConverter, ,
, cm, pt, in px (
).
(, ,
) .
1/96
, (DPI). ,
, .
131
1/96 , ,
96 DPI
. ,
.
1 ,
, , !
, .
. ,
, .
Visibility
, Visibility (
UIElement) ,
. Visibility Boolean,
System.Windows.Visibility ,
:
Visible .
Collapsed .
Hidden , .
(Collapsed) , , ,
(Hidden) . (,
ActualHeight ActualWidth .)
Collapsed Hidden . 4.3,
StackPanel :
<StackPanel Height="100" Background="Aqua">
<Button Visibility="Collapsed">Collapsed Button</Button>
<Button>Below a Collapsed Button</Button>
</StackPanel>
StackPanel :
<StackPanel Height="100" Background="Aqua">
<Button Visibility="Hidden">Hidden Button</Button>
<Button>Below a Hidden Button</Button>
</StackPanel>
.4.3. ,
132
4. ,
(X,Y).
( ),
( ,
, ).
, Frame
workElement, .
, .
HorizontalAlignment VerticalAlignment
,
. ,
System.Windows:
HorizontalAlignment Left, Center, Right, Stretch
VerticalAlignment Top, Center, Bottom, Stretch
Stretch,
.
, HorizontalAlignment ,
Button StackPanel
:
<StackPanel>
<Button HorizontalAlignment="Left"
Background="Red">Left</Button>
<Button HorizontalAlignment="Center"
Background="Orange">Center</Button>
<Button HorizontalAlignment="Right"
Background="Yellow">Right</Button>
<Button HorizontalAlignment="Stretch"
Background="Lime">Stretch</Button>
</StackPanel>
.4.4.
.4.4. HorizontalAlignment
StackPanel
133
, , . ,
VerticalAlignment StackPanel, . 4.4, , , , .
Stretch
(Stretch)
,
Height Width. MaxHeight MaxWidth
, , ,
. MinHeight MinWidth
, ,
. Stretch ,
, Center
( Left,
).
HorizontalAlignment VerticalAlignment, Control
HorizontalContentAlignment VerticalContentAlignment.
. (
, .)
, ,
, ,
, .
HorizontalContentAlignment Left, VerticalContentAlignment Top.
,
. (
,
. ,
, .)
.4.5 , Horizon
talContentAlignment.
XAML-:
<StackPanel>
<Button HorizontalContentAlignment="Left"
Background="Red">Left</Button>
<Button HorizontalContentAlignment="Center"
Background="Orange">Center</Button>
134
4. ,
<Button HorizontalContentAlignment="Right"
Background="Yellow">Right</Button>
<Button HorizontalContentAlignment="Stretch"
Background="Lime">Stretch</Button>
</StackPanel>
.4.5. HorizontalContentAlignment
StackPanel
FlowDirection
FlowDirection, FrameworkElement (
),
. ,
,
. System.
Windows.FlowDirection, : LeftToRight (
FrameworkElement) RightToLeft.
FlowDirection , ,
, RightToLeft.
,
. XAML ,
Top Left,
FlowDirection :
<StackPanel>
<Button FlowDirection="LeftToRight"
HorizontalContentAlignment="Left" VerticalContentAlignment="Top"
Height="40" Background="Red">LeftToRight</Button>
<Button FlowDirection="RightToLeft"
HorizontalContentAlignment="Left" VerticalContentAlignment="Top"
Height="40" Background="Orange">RightToLeft</Button>
</StackPanel>
.4.6.
135
.4.6. FlowDirection
Top Left
, FlowDirection
.
, .
,
, .
FlowDirection
( ).
.
WPF
( System.Windows.Media.Transform),
.
, .
FrameworkElement Transform,
:
LayoutTransform
RenderTransform ( UIElement)
( )
.4.7
RotateTransform LayoutTransform RenderTransform.
.
LayoutTransform, ,
RenderTransform, ,
.
UIElement RenderTransformOrigin,
(
). RotateTransform .4.7
, .
, LayoutTransform,
,
, .
136
4. ,
, LayoutTransform
, RenderTransform
.4.7. LayoutTransform
RenderTransform StackPanel
RenderTransformOrigin System.Windows.Point
(0,0). ,
.4.7. (0,1) , (1,0)
, (1,1) . ,
1, .
. , (0.5,0.5)
. . 4.8 ,
RenderTransformOrigin.
(0,0)
(0,1)
(1,0)
(1,1)
(0.5,0.5)
.4.8. RenderTransformOrigin,
, .4.7
System.Windows.PointConverter RenderTransform
Origin XAML , (
). , Button,
( .4.8):
<Button RenderTransformOrigin="0.5,0.5" Background="Orange">
<Button.RenderTransform>
<RotateTransform Angle="45"/>
</Button.RenderTransform>
Rotated 45
</Button>
137
, ,
. ,
.
,
.
, System.Windows.Media:
RotateTransform
ScaleTransform
SkewTransform
TranslateTransform
MatrixTransform
RotateTransform
RotateTransform,
,
double:
Angle ( 0)
CenterX ( 0)
CenterY ( 0)
(CenterX,CenterY), (0,0),
. CenterX CenterY ,
RenderTransform,
LayoutTransform
.
FAQ
CenterX CenterY
RotateTransform
RenderTransformOrigin UIElement?
, ,
UIElement, CenterX CenterY ,
RenderTransformOrigin.
,
RenderTransform.
CenterX CenterY ,
RenderTransformOrigin .
,
Width, 20, CenterX 20, CenterY 0, (1,0),
138
4. ,
RenderTransformOrigin. ,
RenderTransform (. ) CenterX CenterY
. ,
CenterX CenterY double
, RenderTransformOrigin Point.
RenderTransformOrigin, , ,
CenterX CenterY. ,
, (0.5,0.5),
RenderTransformOrigin, XAML.
CenterX CenterY ,
.
, RenderTransformOrigin
CenterX CenterY .
X Y
.
.4.9. RotateTransform
StackPanel
139
.4.10. TextBlock,
,
RotateTransform ,
,
.
ScaleTransform
ScaleTransform
, .
double:
ScaleX ( 1)
ScaleY ( 1)
CenterX (
0)
CenterY (
0)
ScaleX 0.5, ,
ScaleX 2, . CenterX CenterY
, RotateTransform.
4.2 ScaleTransform
Button StackPanel,
. .4.11 .
4.2. ScaleTransform StackPanel
<StackPanel Width="100">
<Button Background="Red">No Scaling</Button>
<Button Background="Orange">
<Button.RenderTransform>
<ScaleTransform ScaleX="2"/>
</Button.RenderTransform>
X</Button>
<Button Background="Yellow">
<Button.RenderTransform>
<ScaleTransform ScaleX="2" ScaleY="2"/>
</Button.RenderTransform>
X + Y</Button>
<Button Background="Lime">
<Button.RenderTransform>
<ScaleTransform ScaleY="2"/>
140
4. ,
</Button.RenderTransform>
Y</Button>
</StackPanel>
.4.11. , 4.2
.4.12 4.2,
CenterX CenterY.
. ,
, , CenterX 70.
, CenterX , ScaleX
1, CenterY ScaleY 1.
, ScaleTransform
.
.4.12. 4.2,
ScaleTransform Stretch
ScaleTransform LayoutTransform
, ,
,
, .
141
FAQ
, ScaleTransform,
ActualHeight ActualWidth FrameworkElement
RenderSize UIElement?
FrameworkElement
.
RenderTransform LayoutTransform. -
. , .4.11 4.12 ActualHeight, Actual
Width RenderSize .
, , . -
, ,
. , , ,
, .
, ,
.
FAQ
ScaleTransform Margin
Padding?
Padding (
), Margin .
ActualHeight ActualWidth, Padding
, .
SkewTransform
SkewTransform
double:
AngleX ( 0)
AngleY ( 0)
CenterX ( 0)
CenterY ( 0)
. .4.13 Skew
Transform RenderTransform ;
.
142
4. ,
.4.13. SkewTransform
StackPanel
TranslateTransform
TranslateTransform
double:
X ( 0)
Y ( 0)
TranslateTransform ,
LayoutTransform, RenderTransform
.
(, , ). ,
, ,
.
MatrixTransform
MatrixTransform
.
Matrix ( System.Windows.Media.Matrix),
33.
, ,
( ) MatrixTransform.
:
M11
M12
M21
M22
OffsetX
OffsetY
,
Matrix ( )
143
,
.
MatrixTransform
MatrixTransform ,
XAML . (
TransformConverter , Transform,
MatrixTransform.) ,
10 20 ,
:
<Button RenderTransform="1,0,0,1,10,20" />
,
.
LayoutTransform RenderTransform.
MatrixTransform,
. , , Trans
formGroup.
TransformGroup Transform (
, ),
Transform.
Children, XAML :
<Button>
<Button.RenderTransform>
<TransformGroup>
<RotateTransform Angle="45"/>
144
4. ,
.4.14 .
.4.14. , ,
WPF
TransformGroup,
(
MatrixTransform). ,
TransformGroup
. , RotateTransform 45,
90.
,
.
,
Win32, Windows Forms:
!
. StackPanel,
, .
145
FrameworkElement !
, WPF,
, LayoutTransform RenderTransform.
, HwndHost,
GDI- ( 19
). Frame, , ,
HTML- ( 9
), ,
HTML. ScaleTransform
, .
.4.15 , , StackPanel
Frame, - (
100100). ,
, .
.
StackPanel
StackPanel
.4.15. Frame, HTML,
ScaleTransform,
Canvas
StackPanel
WrapPanel
DockPanel
Grid
: ,
,
5.
,
,
. ,
, ,
, - ,
:
,
, , ,
(,
). , ,
( ),
.
1024600. Outlo
ok2010 , , Vi
sual Studio 2010, .
(6001024), Outlook 2010
, ( Visual Studio 2010)
. ( , Visual Studio,
, WPF, Outlook WPF.
,
, ,
.)
WPF ,
.
( System.Windows.Controls)
():
Canvas
StackPanel
Canvas
147
WrapPanel
DockPanel
Grid
.
( ,
) .
,
,
, Visual Studio. , WPF,
.
Canvas
Canvas () . ,
. Canvas
; ,
,
. Canvas
, .
: Left, Top, Right Bottom. Left Right,
,
.
Top Bottom. , ,
,
( Margin
).
( Double.NaN),
( Left Top
0). Canvas 5.1,
.5.1.
5.1. Canvas
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Buttons in a Canvas">
<Canvas>
<Button Background="Red">Left=0, Top=0</Button>
<Button Canvas.Left="18" Canvas.Top="18"
Background="Orange">Left=18, Top=18</Button>
<Button Canvas.Right="18" Canvas.Bottom="18"
Background="Yellow">Right=18, Bottom=18</Button>
<Button Canvas.Right="0" Canvas.Bottom="0"
Background="Lime">Right=0, Bottom=0</Button>
148
5.
Canvas!
Canvas.Left Canvas.Right
.
Canvas.Top Canvas.Bottom Canvas.Bottom.
, .
.5.1 ,
,
Canvas.
5.1. Canvas
Canvas
Margin
. ,
( Top Left),
HorizontalAlignment
VerticalAlignment
.
,
LayoutTransform
. RenderTransform ,
LayoutTransform
Canvas
Canvas
149
Z- (,
) .
XAML .
, , ,
. , .5.1 ,
. ,
( , Canvas), ,
RenderTransform (
.4.7, 4.8, 4.11, 4.12 4.13 ).
Z- ,
ZIndex, Panel (
). ZIndex , 0;
( ).
ZIndex ,
ZIndex ,
.
ZIndex ,
, Canvas :
<Canvas>
<Button Canvas.ZIndex="1" Background="Red">On Top!</Button>
<Button Background="Orange">On Bottom with a Default ZIndex=0</Button>
</Canvas>
ZIndex,
Children
, .
, Z-
ZIndex. ,
,
. C# (
, redButton):
Panel.SetZIndex(redButton, 0);
Canvas
, .
,
. , Canvas
(. 15 ).
150
5.
StackPanel
StackPanel - .
, .
StackPanel,
. StackPanel
,
!
StackPanel
FlowDirection RightToLeft, StackPanel
,
, .
Orientation ( System.
Windows.Controls.Orientation), Horizontal
Vertical. Vertical. .5.2
, Background
Content, StackPanel
.
Vertical
Horizontal
.5.2. StackPanel
.5.2 ,
,
StackPanel.
151
StackPanel
5.2. StackPanel
StackPanel
Margin
. Margin
StackPanel,
HorizontalAlignment
VerticalAlignment
,
(
, ). Orient at i
on="Vertical", VerticalAlignment.
Orientation="Horizontal", Horizontal
Alignment
LayoutTransform
. RenderTransform ,
LayoutTransform ,
.
Stretch RotateTransform SkewTransform,
LayoutTransform,
, 90
LayoutTransform .5.2
. .5.3 , ,
,
,
. StackPanel,
, .
,
LayoutTransform; RenderTransform .
80
90
.5.3. 80, 90
LayoutTransform
152
5.
, System.Windows.Controls. Virtualizing
Panel. VirtualizingStackPanel,
, StackPanel,
, ( ).
VirtualizingStackPanel ,
- , ListBox
. TreeView,
10 .
DataGridCellsPanel DataGridRowsPresenter,
DataGrid (. 11 ,
).
WrapPanel
WrapPanel StackPanel.
,
.
, ,
, , Windows.
StackPanel, WrapPanel
. WrapPanel
, :
Orientation StackPanel ,
Horizontal.
, Win
dows: ,
, .
, Windows:
, ,
.
ItemHeight .
,
VerticalAlignment, Height . ,
ItemHeight, .
ItemWidth .
,
HorizontalAlignment, Width . ,
ItemWidth, .
ItemHeight ItemWidth (,
Double.NaN). WrapPanel
WrapPanel
153
,
,
, .
, .
WrapPanel
. Width (
) Height ( )
Double.MaxValue Double.PositiveInfinity. XAML
x:Static,
System.Double.
.5.4 Wrap
Panel ,
Window. . 5.5
. WrapPanel
ItemHeight/ItemWidth ,
, StackPanel.
.5.4. WrapPanel
.5.5. WrapPanel
.5.3 ,
, WrapPanel.
154
5.
WrapPanel
FlowDirection RightToLeft, WrapPanel
,
.
5.3. WrapPanel
WrapPanel
Margin
. , WrapPanel
,
HorizontalAlignment
VerticalAlignment
. ,
,
StackPanel.
, ItemHeight ItemWidth
,
LayoutTransform
. RenderTransform ,
LayoutTransform ,
, ItemHeight
ItemWidth ( ).
Stretch RotateTransform
SkewTransform, LayoutTransform,
, 90,
StackPanel
WrapPanel
Window,
. , 10.
DockPanel
DockPanel
, . ( Can
vas , ,
.) , DockPanel ,
, .
DockPanel Dock ( System.Win
dows.Controls.Dock),
. : Left (
DockPanel
155
().
.5.6. DockPanel
StackPanel,
HorizontalAlignment VerticalAlign
ment. ,
DockPanel, . .5.7 ,
, , ,
HorizontalAlignment VerticalAlignment:
<DockPanel>
<Button DockPanel.Dock="Top" HorizontalAlignment="Right"
Background="Red">1 (Top, Align=Right)</Button>
<Button DockPanel.Dock="Left" VerticalAlignment="Bottom"
Background="Orange">2 (Left, Align=Bottom)</Button>
<Button DockPanel.Dock="Right" VerticalAlignment="Bottom"
Background="Yellow">3 (Right, Align=Bottom)</Button>
156
5.
, ,
, .
.5.7. DockPanel
DockPanel
Window Page,
, . ,
(Menu),
- , (StatusBar).
.
,
,
. ( , ,
, .)
. 5.8 , . 5.6,
( ). ,
.
157
DockPanel
DockPanel ,
. ,
. . 5.9
DockPanel ,
, .
.5.9.
DockPanel
Margin
. Margin ,
,
HorizontalAlignment
VerticalAlignment
. StackPanel,
. , Dock
Left Right, Horizon
talAlignment, Top Bottom VerticalAlignment.
, ,
, HorizontalAlignment VerticalAlignment
LayoutTransform
. RenderTransform ,
LayoutTransform ,
. Stretch
RotateTransform SkewTransform,
LayoutTransform, ,
90, ,
(
)
158
5.
Grid
Grid () , ,
. ( Visual Studio Expression Blend Grid
.)
,
( WrapPanel). ,
. Grid
TABLE HTML.
, Grid
, Visual Studio.
5.2 42,
Label GroupBox.
5.2. ,
Visual Studio
<Grid Background="LightBlue">
<!-- : -->
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<!-- : -->
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<!-- : -->
<Label Grid.Row="0" Grid.Column="0" Background="Blue"Foreground="White"
HorizontalContentAlignment="Center">Start Page</Label>
<GroupBox Grid.Row="1" Grid.Column="0" Background="White"
Header="Recent Projects">...</GroupBox>
Grid
159
,
RowDefinition ColumnDefinition ,
RowDefinitions ColumnDefinitions. (
, ,
.)
Row Column, ,
0. ,
.
Grid.Row Grid.Column, 0.
, , ,
.
Z-.
Canvas, , ,
, .
.5.10 5.2.
.5.10.
Visual Studio
160
5.
: (Online articles)
. , , Start Page
. ,
Grid: RowSpan ColumnSpan.
RowSpan ColumnSpan 1,
, 1,
, . (
, ,
.) , Group
Box 5.2
Grid.RowSpan="3"
Label
Grid.ColumnSpan="2"
, .5.11.
.5.11 ,
.
,
. ,
,
.
Height Width RowDefini
tion ColumnDefinition Auto,
. 5.2:
<!-- : -->
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
Grid
161
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<!-- : -->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
, .5.12.
.5.12.
FAQ
Grid ,
HTML-?
,
, , ,
. ,
Rectangle,
Fill, . ,
Margin
. ,
, ( Stroke)
Border.
, Rectangle Border
(
ZIndex), Z-
.
162
5.
FrameworkElement, Height Width
RowDefinition ColumnDefinition Auto ( Double.
NaN). , Height Width WPF,
System.Windows.GridLength, double. Grid
RowDefinition ColumnDefinition:
Height Width ,
(
Height Width WPF).
,
Grid
.
Height Width Auto (
),
, , (
Height Width WPF ).
,
. ,
,
- .
Grid
163
) Height
Width,
.
,
.
,
.
:
*,
.
* ,
.
* (, 2* 5.5*),
, ,
*. 2*
* ( , 1*)
. 5.5* 2.75*
.
,
. .5.14
.
*.
. 5.10 5.11
.
.5.14.
164
5.
FAQ
WPF
, HTML?
HTML
100%
HorizontalAlignment VerticalAlignment
Stretch. Grid
,
. , , 25% ,
* ,
3*.
WPF ,
, 100
. ,
(
), , HTML-
.
GridLength
System.Windows.GridLengthConverter "100",
"auto" "2*" GridLength. C# GridLength
.
GridUnitType, .
,
double (, 100):
GridLength length = new GridLength(100);
, GridUnitType:
GridLength length = new GridLength(100, GridUnitType.Pixel);
100 .
GridLength Double.NaN,
GridUnitType.Auto:
GridLength length = new GridLength(0, GridUnitType.Auto);
, , . ,
GridLength.Auto,
GridLength, ,
.
GridUnitType.Star:
GridLength length = new GridLength(2, GridUnitType.Star);
2* XAML. *,
1, GridUnitType.Star.
165
Grid
GridSplitter
Grid
(
, ).
GridSplitter .
Grid GridSplitter,
Grid.Row, Grid.Column, Grid.RowSpan /
Grid.ColumnSpan, . GridSplitter
.
: - .
,
, GridSplitter. . 5.5
, Grid
Splitter (
).
GridSplitter ,
( )
( ).
ColumnSpan RowSpan, .
5.5. , GridSplitter
HorizontalAlignment
VerticalAlignment
Left
Right
Center
Stretch
Top
Bottom
Center
Stretch
,
GridSplitter
,
, GridSplitter
166
5.
GridSplitter
.
. GridSplitter
, (
ZIndex), Z- !
RowDefinitions ColumnDefinitions SharedSizeGroup,
,
/ ,
(
, GridSplitter). SharedSizeGroup
( );
167
Grid
. ,
, .
,
.5.15; SharedSizeGroup :
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Background="Red"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center">1
</Label>
<GridSplitter Grid.Column="0" Width="5"/>
<Label Grid.Column="1" Background="Orange"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center">2
</Label>
<Label Grid.Column="2" Background="Yellow"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center">3
</Label>
</Grid>
,
Label GridSplitter.
.
,
.
GridSplitter
GridSplitter
GridSplitter
.5.15. SharedSizeGroup
GridSplitter ,
Width ( Height )
.
168
5.
.5.16 , ,
SharedSizeGroup.
.
.
,
.
XAML- .
<Grid IsSharedSizeScope="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="myGroup"/>
<ColumnDefinition/>
<ColumnDefinition SharedSizeGroup="myGroup"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Background="Red"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center">1
</Label>
<GridSplitter Grid.Column="0" Width="5"/>
<Label Grid.Column="1" Background="Orange"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center">2
</Label>
<Label Grid.Column="2" Background="Yellow"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center">3
</Label>
</Grid>
GridSplitter
GridSplitter
GridSplitter
.5.16. , .5.15,
SharedSizeGroup
IsSharedSizeScope ,
!
(
), ,
SharedSizeGroup, ,
IsSharedSizeScope true.
Grid
169
Grid, ,
, , :
<StackPanel Grid.IsSharedSizeScope="True">
<Grid>... SharedSizeGroup...</Grid>
<Grid>... SharedSizeGroup...</Grid>
<WrapPanel>
<Grid>... SharedSizeGroup...</Grid>
</WrapPanel>
</StackPanel>
: , ,
, Visual Studio
SharedSizeGroup ,
.
Grid
Grid ,
, , .
, ,
, WrapPanel.
, .
, , .5.12,
, DockPanel StackPanel. DockPanel
, Label,
StackPanel (
GroupBox). GroupBox .
, Grid
, ,
, ,
Grid.
Canvas Grid
HorizontalAlignment VerticalAlignment,
Stretch,
, Canvas. HorizontalAlignment
Left VerticalAlignment Top Canvas.
Left Canvas.Top 0. HorizontalAlignment Right Ver
ticalAlignment Bottom Canvas.Right Can
vas.Bottom 0. , Margin
,
Canvas. Visual Studio,
.
170
5.
StackPanel Grid
, StackPanel,
.
,
,
.
DockPanel Grid
RowSpan ColumnSpan ,
DockPanel. . 5.12 Label, ,
.
.5.6 ,
, Grid.
5.6. Grid
DockPanel
Margin
. Margin ,
HorizontalAlignment
VerticalAlignment
. ,
, ,
.
,
LayoutTransform
. RenderTransform ,
LayoutTransform (
) Margin.
RenderTransform, ,
,
, Grid ,
, ,
StackPanel WrapPanel (
, 10). , DockPanel
Grid, ,
, ,
. ,
RowSpan ColumnSpan.
171
, .
WPF ,
, ,
(. 14 , , )
(. 20
). ,
, .
System.Windows.Controls.Primitives,
ToolBarTray, System.Windows.Controls.
TabPanel
TabPanel WrapPanel, ,
, , .
,
TabControl, .
WrapPanel,
. ,
, .
TabControl 10.
ToolBarPanel
ToolBarPanel, ToolBar,
StackPanel.
(. ) , (
ToolBar). ToolBar
10.
ToolBarOverflowPanel
ToolBarOverflowPanel WrapPanel,
. ToolBar
.
WrapPanel WrapWidth,
, Padding. ,
WrapPanel.
ToolBarTray
ToolBarTray ToolBar (
InvalidOperationException
). ToolBar (
172
5.
) ,
, ToolBar.
UniformGrid
UniformGrid , .
Grid,
*, . - UniformGrid
double, ,
RowDefinitions ColumnDefi
nitions. , ;
,
.
, (
), Uniform
Grid . ,
2 4, 22, 5 9
33, 10 16 44 .. .5.17 ,
UniformGrid, .
.5.17. UniformGrid
SelectiveScrollingGrid
SelectiveScrollingGrid Grid,
DataGridRow.
Grid ,
. Selective
ScrollingOrientation, :
None
Horizontal
Vertical
Both .
173
,
.
, , ,
, .
, , ,
. ListBox
, Window.
.
:
.
WrapPanel ( TabPanel Tool
BarOverflowPanel).
( 11).
.
TextBlock AccessText,
TextTrimming ( System.Windows.TextTrimming), None
( ), CharacterEllipsis WordEllipsis.
(),
.
,
, .
(,
DockPanel). ,
- .
, UIElement, ClipTo
Bounds, ,
. ,
Window Page, .
Window. (
7 .)
, ClipToBounds,
. Canvas UniformGrid
, ClipToBounds
true, .
174
5.
.5.18 , ClipToBounds
, Canvas ( ).
ClipToBounds="False"
ClipToBounds="True"
.5.18. ClipToBounds ,
, , ClipToBounds true,
Canvas ; Height Width 0,
, Canvas !
, Control,
ClipToBounds. , Button
ClipToBounds false. .5.19 , ,
true,
ScaleTransform (
RenderTransform).
ClipToBounds="False"
ClipToBounds="True"
.5.19. ClipToBounds
(, Button)
Canvas
. ,
Grid ,
Canvas ( ), Canvas Button.
, ,
, Grid, .
, ,
, RowSpan / ColumnSpan.
175
RenderTransform!
ScaleTransform
RenderTransform, ,
( , Window
Page). ScaleTransform RenderTransform
.
- , ,
,
! ,
RenderTransform .
Scale
Transform, LayoutTransform ,
.
, - . WPF
System.Windows.
Controls.ScrollViewer, . ScrollVie
wer ScrollBar,
, .
ScrollViewer Content,
- ,
. Content XAML,
, ,
:
<Window Title="Using ScrollViewer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<ScrollViewer>
<StackPanel>
...
</StackPanel>
</ScrollViewer>
</Window>
176
5.
.5.20. ScrollViewer ,
ScrollViewer
, VerticalScroll
BarVisibility HorizontalScrollBarVisibility.
ScrollBarVisibility, :
Visible , .
,
. ( , Disabled
ScrollBarVisibility.)
Auto ,
. .
Hidden , ,
.
.
Disabled ,
, ,
. ,
.
VerticalScrollBarVisibility Visible,
HorizontalScrollBarVisibility Auto,
.
ScrollViewer Hid
den Disabled . , .5.21
Window, ScrollViewer,
WrapPanel. ,
HorizontalScrollBarVisibility Hidden,
Disabled.
Hidden WrapPanel ,
( HorizontalScrollBarVisibility Visible Auto),
.
Disabled ,
177
Window, ,
ScrollViewer .
HorizontalScrollBarVisibility="Hidden"
HorizontalScrollBarVisibility="Disabled"
.5.21. ,
HorizontalScrollBarVisibility
WrapPanel
3 WPF ,
ListBox ScrollViewer.
, VerticalScroll
BarVisibility HorizontalScrollBarVisibility
ScrollViewer:
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
...
</ListBox>
,
. , ,
. ,
.
.5.22 ,
( XAML
20). Canvas,
Window. ,
( Grid, Canvas).
, .
178
5.
.5.22. , ,
ScaleTransform
( ),
. ,
System.Windows.Controls.Viewbox
.
Viewbox ,
, .
Border, System.Windows.Controls.Decorator.
Viewbox ( )
, .
Stretch, ,
.
System.Windows.Media.Stretch
( .5.23, Viewbox
Canvas):
None . ,
Viewbox .
Fill ,
Viewbox.
.
Uniform ,
Viewbox . ,
Viewbox ,
.
.
UniformToFill ,
Viewbox . ,
Viewbox ,
.
, ,
,
179
Stretch="None"
Stretch="Fill"
Stretch="Uniform"
Stretch="UniformToFill"
.5.23. Stretch
Viewbox
Viewbox , :
, .
StretchDirection, System.Windows.Controls.Stretch
Direction :
UpOnly , .
, Viewbox .
DownOnly , .
, Viewbox .
Both
Stretch.
.
,
. Window,
.5.20:
180
5.
ScrollViewer Viewbox ( ),
, .5.24:
<Window Title="Using Viewbox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Viewbox>
<StackPanel>
...
</StackPanel>
</Viewbox>
</Window>
, !
Viewbox !
Viewbox , ,
,
WrapPanel. ,
, ,
( ). .5.25
WrapPanel,
.5.21, ScrollViewer Viewbox.
181
182
5.
: ,
,
WPF ,
.
Visual Studio ,
. ,
, ,
. ,
, . .5.275.33
.
.5.27. ,
.5.28. Toolbox,
Toolbox, ,
: , ,
183
.5.29. ,
.5.30. Toolbox,
,
, Toolbox
.5.31. -
GridSplitter,
184
5.
,
.
( .5.33), , Grid
, , .
?
,
Grid GridSplitter.
.
, .
.
, (
: , ,
185
), SharedSizeGroup. .5.34
, .
0
,
Width=*
SharedSizeGroup #1
1
1
Width=*
Width=Auto
SharedSizeGroup #2
2
2
Width=*
Width=Auto
.5.34. Grid
, ,
( 0) , ,
, , .
1
2 Collapsed Visible.
, ( ,
, , 0).
, .
1
0 1. 0
186
5.
, 1.
, SharedSizeGroup,
1 .
2,
(0 1).
,
0
, . ,
, , .
( ?)
,
, . Z- 0
, Z- ,
.
5.3 XAML- , .5.27
5.33, .
, ( http://
informit.com/title/9780672331190).
5.3. VisualStudioLikePanes.xaml XAML-
, .5.275.33
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Application with Collapsible, Dockable, Resizable Panes">
<DockPanel>
<Menu DockPanel.Dock="Top">
...
</Menu>
<!-- , : -->
<StackPanel Name="buttonBar" Orientation="Horizontal" DockPanel.Dock="Right">
<StackPanel.LayoutTransform>
<RotateTransform Angle="90"/>
</StackPanel.LayoutTransform>
<Button Name="pane1Button" MouseEnter="pane1Button_MouseEnter">
Toolbox
</Button>
<Button Name="pane2Button" MouseEnter="pane2Button_MouseEnter">
Solution Explorer
</Button>
</StackPanel>
<!-- , , DockPanel: -->
<Grid Name="parentGrid" Grid.IsSharedSizeScope="True">
<!-- 0: -->
<Grid Name="layer0" MouseEnter="layer0_MouseEnter">
: , ,
187
... ( , 5.2)
</Grid>
<!-- 1: -->
<Grid Name="layer1" Visibility="Collapsed">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition SharedSizeGroup="column1" Width="auto"/>
</Grid.ColumnDefinitions>
<!-- 0 , 1
Grid GridSplitter: -->
<Grid Grid.Column="1" MouseEnter="pane1_MouseEnter"
Background="{DynamicResource
{x:Static SystemColors.ActiveCaptionBrushKey}}">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<!-- 0 ,
1 - : -->
<DockPanel Grid.Row="0">
<Button Name="pane1Pin" Width="26" DockPanel.Dock="Right"
Click="pane1Pin_Click" Background="White">
<Image Name="pane1PinImage" Source="pinHorizontal.gif"/>
</Button>
<TextBlock Padding="8" TextTrimming="CharacterEllipsis"
Foreground="{DynamicResource
{x:Static SystemColors.ActiveCaptionTextBrushKey}}"
DockPanel.Dock="Left">Toolbox</TextBlock>
</DockPanel>
... ( 1)
</Grid>
<GridSplitter Width="5" Grid.Column="1" HorizontalAlignment="Left"/>
</Grid>
<!-- 2: -->
<Grid Name="layer2" Visibility="Collapsed">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition SharedSizeGroup="column2" Width="auto"/>
</Grid.ColumnDefinitions>
<!-- 0 , 1
Grid GridSplitter: -->
<Grid Grid.Column="1" MouseEnter="pane2_MouseEnter"
Background="{DynamicResource
{x:Static SystemColors.ActiveCaptionBrushKey}}">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
188
5.
<!-- 0 ,
1 2 - : -->
<DockPanel Grid.Row="0">
<Button Name="pane2Pin" Width="26" DockPanel.Dock="Right"
Click="pane2Pin_Click" Background="White">
<Image Name="pane2PinImage" Source="pinHorizontal.gif"/>
</Button>
<TextBlock Padding="8" TextTrimming="CharacterEllipsis"
Foreground="{DynamicResource
{x:Static SystemColors.ActiveCaptionTextBrushKey}}"
DockPanel.Dock="Left">Solution Explorer
</TextBlock>
</DockPanel>
... ( 1)
</Grid>
<GridSplitter Width="5" Grid.Column="1" HorizontalAlignment="Left"/>
</Grid>
</Grid>
</DockPanel>
</Window>
Window DockPanel,
, StackPanel, (
90 RotateTransform), ,
, . , Menu
DockPanel , StackPanel,
.
- ,
.
GridSplitter ,
.
Label, TextBlock,
TextTrimming="CharacterEllipsis",
,
. .
5.4 C#,
5.3.
5.4. VisualStudioLikePanes.xaml.cs C#-
, .5.275.33
using
using
using
using
System;
System.Windows;
System.Windows.Controls;
System.Windows.Media.Imaging;
: , ,
ColumnDefinition column2CloneForLayer0;
ColumnDefinition column2CloneForLayer1;
public MainWindow()
{
InitializeComponent();
// , ,
//
column1CloneForLayer0 = new ColumnDefinition();
column1CloneForLayer0.SharedSizeGroup = "column1";
column2CloneForLayer0 = new ColumnDefinition();
column2CloneForLayer0.SharedSizeGroup = "column2";
column2CloneForLayer1 = new ColumnDefinition();
column2CloneForLayer1.SharedSizeGroup = "column2";
}
// : / ( 1)
public void pane1Pin_Click(object sender, RoutedEventArgs e)
{
if (pane1Button.Visibility == Visibility.Collapsed)
UndockPane(1);
else
DockPane(1);
}
// : / ( 2)
public void pane2Pin_Click(object sender, RoutedEventArgs e)
{
if (pane2Button.Visibility == Visibility.Collapsed)
UndockPane(2);
else
DockPane(2);
}
// 1,
public void pane1Button_MouseEnter(object sender, RoutedEventArgs e)
{
layer1.Visibility = Visibility.Visible;
// Z-, :
Grid.SetZIndex(layer1, 1);
Grid.SetZIndex(layer2, 0);
// ,
if (pane2Button.Visibility == Visibility.Visible)
layer2.Visibility = Visibility.Collapsed;
}
// 2,
public void pane2Button_MouseEnter(object sender, RoutedEventArgs e)
189
190
5.
{
layer2.Visibility = Visibility.Visible;
// Z-, :
Grid.SetZIndex(layer2, 1);
Grid.SetZIndex(layer1, 0);
// ,
if (pane1Button.Visibility == Visibility.Visible)
layer1.Visibility = Visibility.Collapsed;
}
// ,
// 0
public void layer0_MouseEnter(object sender, RoutedEventArgs e)
{
if (pane1Button.Visibility == Visibility.Visible)
layer1.Visibility = Visibility.Collapsed;
if (pane2Button.Visibility == Visibility.Visible)
layer2.Visibility = Visibility.Collapsed;
}
// , ,
// 1
public void pane1_MouseEnter(object sender, RoutedEventArgs e)
{
// ,
if (pane2Button.Visibility == Visibility.Visible)
layer2.Visibility = Visibility.Collapsed;
}
// , ,
// 2
public void pane2_MouseEnter(object sender, RoutedEventArgs e)
{
// ,
if (pane1Button.Visibility == Visibility.Visible)
layer1.Visibility = Visibility.Collapsed;
}
// ,
//
public void DockPane(int paneNumber)
{
if (paneNumber == 1)
{
pane1Button.Visibility = Visibility.Collapsed;
pane1PinImage.Source = new BitmapImage(new Uri("pin.gif",
UriKind.Relative));
// 0:
: , ,
layer0.ColumnDefinitions.Add(column1CloneForLayer0);
// 1,
// 2 :
if (pane2Button.Visibility == Visibility.Collapsed)
layer1.ColumnDefinitions.Add(column2CloneForLayer1);
}
else if (paneNumber == 2)
{
pane2Button.Visibility = Visibility.Collapsed;
pane2PinImage.Source = new BitmapImage(new Uri("pin.gif",
UriKind.Relative));
// 0:
layer0.ColumnDefinitions.Add(column2CloneForLayer0);
// 1,
// 1 :
if (pane1Button.Visibility == Visibility.Collapsed)
layer1.ColumnDefinitions.Add(column2CloneForLayer1);
}
}
// ,
//
public void UndockPane(int paneNumber)
{
if (paneNumber == 1)
{
layer1.Visibility = Visibility.Visible;
pane1Button.Visibility = Visibility.Visible;
pane1PinImage.Source = new BitmapImage
(new Uri("pinHorizontal.gif", UriKind.Relative));
// 0 1:
layer0.ColumnDefinitions.Remove(column1CloneForLayer0);
// , Remove
// :
layer1.ColumnDefinitions.Remove(column2CloneForLayer1);
}
else if (paneNumber == 2)
{
layer2.Visibility = Visibility.Visible;
pane2Button.Visibility = Visibility.Visible;
pane2PinImage.Source = new BitmapImage
(new Uri("pinHorizontal.gif", UriKind.Relative));
// 0 1:
layer0.ColumnDefinitions.Remove(column2CloneForLayer0);
191
192
5.
// , Remove
// :
layer1.ColumnDefinitions.Remove(column2CloneForLayer1);
}
}
}
C# . ,
,
.
, , ,
, ,
. , StackPanel
,
.
5.4 ( ),
.
, ,
.
,
.
Grid WPF
.
WPF ,
.
,
.
: , ,
6.
, , WPF,
.
WPF
.
: , , .
3 WPF ,
WPF
.NET. WPF
.
.
,
.
( )
WPF. ,
Button Click
MouseLeftButtonDown KeyDown.
, ,
ButtonChrome
TextBlock.
, Button
. Stop,
(. 2 XAML),
194 6. : , ,
, Rectangle.
, Button
. (,
Rectangle
Button, .)
, , Button,
( , 14
, , ),
Click .
,
.
. ,
, ,
.
About
3.
.NET.
, .NET- ( XAML) ,
.
WPF.
6.1 Click
Button. ( Click
Button, .)
,
DependencyProperty
Property.
RoutedEvent
Event. , ,
,
.NET ,
XAML-
.
, ,
AddHandler RemoveHandler.
6.1.
public class Button : ButtonBase
{
//
public static readonly RoutedEvent ClickEvent;
195
static Button()
{
//
Button.ClickEvent = EventManager.RegisterRoutedEvent("Click",
RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Button));
...
}
// .NET ()
public event RoutedEventHandler Click
{
add { AddHandler(Button.ClickEvent, value); }
remove { RemoveHandler(Button.ClickEvent, value); }
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
...
//
RaiseEvent(new RoutedEventArgs(Button.ClickEvent, this));
...
}
...
}
. RoutingStrategy:
Tunneling ,
, ,
(
).
Bubbling -,
,
, (
).
196 6. : , ,
Direct -.
.NET; ,
,
.
,
.NET:
System.Object, sender, (
e) , System.EventArgs.
sender ,
. e RoutedEventArgs
( ) EventArgs,
:
Source ,
.
OriginalSource ,
(, Button
TextBlock ButtonChrome).
Handled , true
, .
.
RoutedEvent (, Button.
ClickEvent),
,
.
Source OriginalSource
, . ,
,
.
(, Click
), Source OriginalSource
.
UIElement
, , .
, .
,
Preview.
. ,
PreviewMouseMove
MouseMove.
, , ,
,
. WPF
197
(
),
, (preview
). , ,
TextBox, ,
(,
). KeyDown,
, , ,
TextBox. PreviewKeyDown,
,
KeyDown.
TextBox KeyDown
.
,
6.2 About 3
Window MouseRightButtonDown. 6.3
C#.
6.2. About
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="AboutDialog"
MouseRightButtonDown="AboutDialog_MouseRightButtonDown"
Title="About WPF 4 Unleashed" SizeToContent="WidthAndHeight"
Background="OrangeRed">
<StackPanel>
<Label FontWeight="Bold" FontSize="20" Foreground="White">
WPF 4 Unleashed
</Label>
<Label> 2010 SAMS Publishing</Label>
<Label>Installed Chapters:</Label>
<ListBox>
<ListBoxItem>Chapter 1</ListBoxItem>
<ListBoxItem>Chapter 2</ListBoxItem>
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button MinWidth="75" Margin="10">Help</Button>
<Button MinWidth="75" Margin="10">OK</Button>
</StackPanel>
<StatusBar>You have successfully registered this product.</StatusBar>
</StackPanel>
</Window>
6.3. 6.2
using
using
using
using
System.Windows;
System.Windows.Input;
System.Windows.Media;
System.Windows.Controls;
198 6. : , ,
public partial class AboutDialog : Window
{
public AboutDialog()
{
InitializeComponent();
}
void AboutDialog_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
//
this.Title = "Source = " + e.Source.GetType().Name + ", OriginalSource = " +
e.OriginalSource.GetType().Name + " @ " + e.Timestamp;
// Control
Control source = e.Source as Control;
// -
if (source.BorderThickness != new Thickness(5))
{
source.BorderThickness = new Thickness(5);
source.BorderBrush = Brushes.Black;
}
else
source.BorderThickness = new Thickness(0);
}
}
MouseRightButtonDown Window,
:
( )
,
. .6.1. ,
Label Source , OriginalSource
TextBlock.
.6.1. About
199
, :
Window MouseRightButtonDown,
ListBoxItem. , ListBoxItem
, MouseLeftButtonDown ( ),
.
Window MouseRightButtonDown Button,
.
Button,
.3.3. Window, Label, ListBox, ListBox
Item StatusBar, Button Border.
!
true Handled RoutedEventArgs
, , ,
,
!
AddHandler,
handledEventsToo.
, 6.2
AddHandler AboutDialog:
public AboutDialog()
{
InitializeComponent();
this.AddHandler(Window.MouseRightButtonDownEvent,
new MouseButtonEventHandler(AboutDialog_MouseRightButtonDown), true);
}
true, AboutDia
log_MouseRightButtonDown
ListBoxItem !
,
, , - .
Preview- .
,
.
, ,
.
200 6. : , ,
, .
WPF
, !
.
,
(
). 6.4 About,
Window Selec
tionChanged, ListBox, Click,
Button. Window
SelectionChanged Click,
, ,
. 6.5 ,
.
MessageBox , .
6.4. About
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="AboutDialog"
ListBox.SelectionChanged="ListBox_SelectionChanged"
Button.Click="Button_Click"
Title="About WPF Unleashed" SizeToContent="WidthAndHeight"
Background="OrangeRed">
<StackPanel>
<Label FontWeight="Bold" FontSize="20" Foreground="White">
WPF 4 Unleashed
</Label>
<Label> 2010 SAMS Publishing</Label>
<Label>Installed Chapters:</Label>
<ListBox>
<ListBoxItem>Chapter 1</ListBoxItem>
<ListBoxItem>Chapter 2</ListBoxItem>
</ListBox>
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center">
<Button MinWidth="75" Margin="10">Help</Button>
<Button MinWidth="75" Margin="10">OK</Button>
</StackPanel>
<StatusBar>You have successfully registered this product.</StatusBar>
</StackPanel>
</Window>
201
6.5. 6.4
using System.Windows;
using System.Windows.Controls;
public partial class AboutDialog : Window
{
public AboutDialog()
{
InitializeComponent();
}
void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
MessageBox.Show("You just selected " + e.AddedItems[0]);
}
void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("You just clicked " + e.Source);
}
}
.
, 6.4,
, XAML .NET SelectionChanged,
ListBox, .NET Click, Button.
AddHandler,
Window.
Window:
public AboutDialog()
{
InitializeComponent();
this.AddHandler(ListBox.SelectionChangedEvent,
new SelectionChangedEventHandler(ListBox_SelectionChanged));
this.AddHandler(Button.ClickEvent, new RoutedEventHandler(Button_Click));
}
,
.
RoutedEvent, , ,
RoutedEventArgs (
, KeyEventArgs, MouseButtonEventArgs ..),
.
202 6. : , ,
, 6.5 ,
ListBox.SelectionChanged Button.Click GenericHandler:
void GenericHandler(object sender, RoutedEventArgs e)
{
if (e.RoutedEvent == Button.ClickEvent)
{
MessageBox.Show("You just clicked " + e.Source);
}
else if (e.RoutedEvent == ListBox.SelectionChangedEvent)
{
SelectionChangedEventArgs sce = (SelectionChangedEventArgs)e;
if (sce.AddedItems.Count > 0)
MessageBox.Show("You just selected " + sce.AddedItems[0]);
}
}
.NET Framework
, ,
(,
RoutedEventArgs SelectionChangedEventArgs). GenericHandler
RoutedEventArgs ,
, SelectionChanged.
, UIEle
ment, KeyDown KeyUp
PreviewKeyDown PreviewKeyUp.
KeyEventArgs, ,
:
Key, ImeProcessedKey, DeadCharProcessedKey, SystemKey ,
Key,
. Key ,
.
(Input Method Editor IME),
ImeProcessedKey.
, Key DeadCharProcessed,
DeadCharProcessedKey.
, Alt, Key System,
SystemKey.
IsUp, IsDown, IsToggled ,
,
. ( KeyDown, ,
!) IsToggled
, Caps Lock Scroll Lock.
203
,
System.Windows.Input PrimaryDevice ( Keyboard
Device).
KeyStates KeyStates, ,
, Alt+A
- :
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyboardDevice.Modifiers == ModifierKeys.Alt
&& (e.Key == Key.A || e.SystemKey == Key.A))
{
204 6. : , ,
// Alt+A Alt+A
}
base.OnKeyDown(e);
}
FAQ
, Alt, Ctrl Shift : ?
Key : LeftAlt RightAlt, LeftCtrl
RightCtrl, LeftShift RightShift. Alt
, System, ,
Alt . ,
IsKeyDown KeyboardDevice ( IsKeyUp IsKeyToggled),
, Alt.
[]Alt+A:
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyboardDevice.Modifiers == ModifierKeys.Alt
&& (e.Key == Key.A || e.SystemKey == Key.A)
&& e.KeyboardDevice.IsKeyDown(Key.LeftAlt))
{
// LeftAlt+A
}
base.OnKeyDown(e);
}
,
, .
( ,
WPF, 19
.) UIElement ,
. , ,
Focusable, true.
FocusableChanged.
UIElement ,
. IsKeyboardFocused,
, , IsKeyboardFo
cusWithin, ,
, . ( ;
, Focus MoveFocus.)
IsKeyboardFocusedChanged, IsKey
boardFocusWithinChanged, GotKeyboardFocus, LostKeyboardFocus, PreviewGotKeyboard
Focus PreviewLostKeyboardFocus.
205
UIElement :
MouseEnter MouseLeave
MouseMove PreviewMouseMove
MouseLeftButtonDown, MouseRightButtonDown, MouseLeftButtonUp, MouseRightBut
tonUp MouseDown MouseUp, Preview-
MouseWheel PreviewMouseWheel
MouseEnter MouseLeave
, Is
MouseOver.
UIElement IsMouseDirectlyOver (
IsMouseDirectlyOverChanged),
. ,
, .
FAQ
?
MouseDown
MouseUp ( Preview-). EventArgs,
, , ,
: LeftButton, RightButton, MiddleButton, XButton1 XButton2.
, (
, ),
false IsHitTestVisible.
, null- !
, IsHitTestVisible
false , ,
, . Visibility
Collapsed, ,
Opacity 0 .
, Background, Fill Stroke null.
206 6. : , ,
. ,
Background, Fill Stroke Transparent (
), . (null (Transparent) ,
.)
MouseEventArgs
( IsMouseDirectly
OverChanged) MouseEventArgs.
MouseButtonState,
: LeftButton, RightButton, MiddleButton, XBut
ton1 XButton2. MouseButtonState : Pres
sed Released. MouseEventArgs GetPosition,
Point X Y,
.
GetPosition , ,
:
UIElement. ,
null.
.
MouseWheel PreviewMouseWheel
MouseWheelEventArgs, MouseEventArgs.
Delta, ,
. 12
MouseUp/MouseDown MouseButtonEventArgs,
MouseEventArgs. ChangedButton,
, (
MouseButton); ButtonState, ,
; ClickCount.
ClickCount ,
, ,
,
( ). Button
Click, MouseLeftButtonDown,
Control MouseDoubleClick,
ClickCount 2 MouseLeftButtonDown, PreviewMouse
DoubleClick, PreviewMouseLeftButtonDown.
,
, ,
..
207
Canvas
, Width Height!
, Width Height
Canvas 0, .
Canvas ( , )
, WidthHeight
( , Background null ).
Canvas
.
UIElement
:
DragEnter, DragOver, DragLeave, PreviewDragEnter, PreviewDragOver Pre
viewDragLeave
Drop PreviewDrop
QueryContinueDrag PreviewQueryContinueDrag
Win32, .
, true
AllowDrop.
Drag
EventArgs, :
GetPosition , MouseEventArgs
Data IDataObject,
Win32
Effects AllowedEffects DragDropEffects,
Copy, Move, Link, Scroll, All None
KeyStates (DragDropKeyStates),
, -
: LeftMouseButton, RightMouseButton, Midd
leMouseButton, ShiftKey, ControlKey, AltKey None
QueryContinueDrag PreviewQueryContinueDrag ,
-
. .
QueryContinueDragEvent
Args, :
KeyStates DragEventArgs
208 6. : , ,
EscapePressed , ,
Esc
Action , ,
; Drag
Action Continue, Drop Cancel
,
System.Windows.Input.Mouse.
Mouse.GetPosition
. GetPo
sition DragEventArgs, , ,
, PInvoke Win32
API GetCursorPos, .
,
UIElement, . ,
MouseLeftButtonDown, MouseMove Mouse
LeftButtonUp.
MouseLeftButtonDown ,
MouseMove ,
, true, MouseLeft
ButtonUp , .
, ,
, ,
.
, WPF UIElement
. ,
,
.
.
UIElement: CaptureMouse ReleaseMouseCapture. (, ,
, , ,
IsMouseCaptured IsMouseCaptureWithin GotMouseCapture, LostMouseCap
ture, IsMouseCaptureChanged IsMouseCaptureWithinChanged.)
MouseLeftButtonDown MouseLeftButtonUp.
209
MouseMove.
, , ,
RenderTransform LayoutTransform.
WPF , ,
, Tablet PC. (
.)
,
, MouseDown, MouseMove MouseUp.
,
Tablet PC.
,
, System.
Windows.Input.StylusDevice. .
StylusDevice MouseEventArgs
. ( ,
null.)
System.Win
dows.Input.Stylus
CurrentStylusDevice
. ( , null.)
, .
,
.
FAQ
, ,
. - ?
,
( ,
):
.
,
.
, ,
. ,
, ,
, Windows7 WPF3.5
SP1.
210 6. : , ,
StylusDevice
StylusDevice , :
Inverted , ,
( ).
InAir , , .
,
,
.
StylusButtons StylusButton. ,
. StylusBut
ton Name Guid,
StylusButtonState, : Up Down.
TabletDevice System.Win
dows.Input.TabletDevice,
(,
). Type Stylus Touch
.
StylusDevice GetPosition, ,
. GetStylus
Points, StylusPoint.
StylusPoint :
X ,
.
Y ,
.
PressureFactor 0 1, ,
. ,
(
). ,
PressureFactor 0.5.
GetStylusPoints (
), , - .
, MouseMove
.
:
StylusEnter StylusLeave
StylusMove PreviewStylusMove
StylusInAirMove PreviewStylusInAirMove
StylusDown, StylusUp, PreviewStylusDown PreviewStylusUp
211
tonUp
StylusSystemGesture PreviewStylusSystemGesture
StylusInRange, StylusOutOfRange, PreviewStylusInRange PreviewStylusOutOfRange
GotStylusCapture LostStylusCapture
StylusEventArgs,
StylusDevice StylusDevice.
InAir, Inverted, GetPosition GetStylusPoints,
StylusDevice.
StylusEventArgs:
StylusDownEventArgs StylusDown Pre
view
StylusDown; TapCount,
ClickCount .
StylusButtonEventArgs StylusButtonDown,
StylusButtonUp Preview-; StylusButton,
.
StylusSystemGestureEventArgs Stylus
Sys
temGesture PreviewStylusSystemGesture; SystemGesture,
SystemGesture
: Tap, RightTap, TwoFingerTap, Drag, RightDrag, Flick, HoldEnter,
HoldLeave, HoverEnter, HoverLeave, None.
Windows 7 ,
, ,
WPF4. :
.
, ,
, .
212 6. : , ,
,
, .
( )
, Multi
Point Mouse SDK (http://microsoft.com/multipoint/mouse-sdk),
25 !
. MultiPoint
;
http://blogs.msdn.com/ansont/archive/2010/01/30/custom-touch-devices.aspx.
:
TouchEnter TouchLeave
TouchMove PreviewTouchMove
TouchDown, TouchUp, PreviewTouchDown PreviewTouchUp
GotTouchCapture LostTouchCapture
,
. ,
.
TouchEventArgs,
:
GetTouchPoint , TouchPoint.
, ,
. GetPosition .
GetIntermediateTouchPoints ,
TouchPoint , ,
. GetStylus
Points .
TouchDevice , TouchDevice.
TouchPoint Position, Size,
, ,
Bounds, . ,
, ,
, TouchDevice
Action, : Down, Move, Up
( TouchAction).
TouchDevice,
Id. (
213
TouchDevice)
.
6.6 TouchDown, TouchMove TouchUp
( !)
.
, Canvas canvas:
<Window x:Class="TouchEvents.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Touch Events">
<Canvas Name="canvas">
<Canvas.Background>
<LinearGradientBrush>
<GradientStop Color="Black"/>
<GradientStop Color="Red" Offset="1"/>
</LinearGradientBrush>
</Canvas.Background>
</Canvas>
</Window>
.6.2.
.6.2.
214 6. : , ,
using
using
using
using
System.Windows.Controls;
System.Windows.Input;
System.Windows.Media;
System.Windows.Media.Imaging;
namespace TouchEvents
{
public partial class MainWindow : Window
{
// TouchDevice
Dictionary<TouchDevice, Image> fingerprints =
new Dictionary<TouchDevice, Image>();
public MainWindow()
{
InitializeComponent();
}
protected override void OnTouchDown(TouchEventArgs e)
{
base.OnTouchDown(e);
//
canvas.CaptureTouch(e.TouchDevice);
//
Image fingerprint = new Image { Source = new BitmapImage(
new Uri("pack://application:,,,/fingerprint.png")) };
//
TouchPoint point = e.GetTouchPoint(canvas);
fingerprint.RenderTransform = new TranslateTransform(
point.Position.X, point.Position.Y);
//
fingerprints[e.TouchDevice] = fingerprint;
canvas.Children.Add(fingerprint);
}
protected override void OnTouchMove(TouchEventArgs e)
{
base.OnTouchMove(e);
if (e.TouchDevice.Captured == canvas)
{
//
Image fingerprint = fingerprints[e.TouchDevice];
TranslateTransform transform =
fingerprint.RenderTransform as TranslateTransform;
//
TouchPoint point = e.GetTouchPoint(canvas);
transform.X = point.Position.X;
215
transform.Y = point.Position.Y;
}
}
protected override void OnTouchUp(TouchEventArgs e)
{
base.OnTouchUp(e);
//
canvas.ReleaseTouchCapture(e.TouchDevice);
//
canvas.Children.Remove(fingerprints[e.TouchDevice]);
fingerprints.Remove(e.TouchDevice);
}
}
}
, ,
TouchDown, TouchUp.
,
OnXXX Window.
OnTouchDown ,
. , ,
,
. Canvas .
Image ,
12 ,
TranslateTransform,
, .
TouchDevice.
OnTouchMove ,
TouchDevice, TouchPoint. ,
TouchDevice, .
OnTouchUp ,
Image .
Silverlight 4 . ,
WPF, Silver
light, FrameReported,
. FrameReported
System.Windows.Input.Touch TouchPoint
. ; ,
, .
216 6. : , ,
.
, .
, ,
,
. ,
TranslateTransform, RotateTransform Scale
Transform . ,
, .
, ,
, ,
, ,
.
,
, .
, WPF
, ,
. :
ManipulationStarting ManipulationStarted
ManipulationDelta
ManipulationCompleted
, ,
. , IsManipu
lationEnabled true
.
TouchDown,
ManipulationStarting, ManipulationStarted.
TouchMove ManipulationDelta, ,
, ManipulationCompleted. ManipulationStarting
ManipulationStarted
,
.
ManipulationDelta
, ;
.
ManipulationDelta:
Translation Vector, X Y
Scale Vector
217
Rotation double,
Expansion Vector, Scale
; ,
,
, ManipulationDeltaEventArgs,
ManipulationDelta, ManipulationDelta:
DeltaManipulation ( ,
) CumulativeManipulation (
, ManipulationStarted). ,
, ,
!
6.7 Window.
,
: ,
.
<Window x:Class="ManipulationEvents.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Manipulation Events">
<Canvas Name="canvas" IsManipulationEnabled="True">
<Image Name="photo" Source="photo.jpg">
<Image.RenderTransform>
<MatrixTransform/>
</Image.RenderTransform>
</Image>
</Canvas>
</Window>
.6.3.
.6.3. ,
ManipulationDelta
218 6. : , ,
6.7. MainWindow.xaml.cs ManipulationDelta
,
using
using
using
using
System;
System.Windows;
System.Windows.Input;
System.Windows.Media;
namespace ManipulationEvents
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
canvas.ManipulationDelta += Canvas_ManipulationDelta;
}
void Canvas_ManipulationDelta(object sender,
ManipulationDeltaEventArgs e)
{
MatrixTransform transform = photo.RenderTransform as MatrixTransform;
if (transform != null)
{
// ,
// MatrixTransform
Matrix matrix = transform.Matrix;
matrix.Translate(e.DeltaManipulation.Translation.X,
e.DeltaManipulation.Translation.Y);
matrix.RotateAt(e.DeltaManipulation.Rotation,
e.ManipulationOrigin.X, e.ManipulationOrigin.Y);
matrix.ScaleAt(e.DeltaManipulation.Scale.X,
e.DeltaManipulation.Scale.Y,
e.ManipulationOrigin.X, e.ManipulationOrigin.Y);
transform.Matrix = matrix;
e.Handled = true;
}
}
}
}
Image photo
MatrixTransform, RenderTransform,
ManipulationDelta Matrix ,
ManipulationDeltaEventArgs. RotateAt ScaleAt
(e.Manipulation
Origin).
. , IsManipulationEnab
led=True; XAML-
Canvas, Image.
219
, Manipula
tionStarting ManipulationStartingEventArgs.Manipulation
Container .
, ,
.
, , ,
.
, ManipulationInertia
Starting . Manipu
lationInertiaStarting ManipulationCompleted
, .
ManipulationInertiaStarting ,
, - ManipulationIner
tiaStartingEventArgs.TranslationBehavior, ManipulationInertiaStartingEventArgs.
RotationBehavior ManipulationInertiaStartingEventArgs.ExpansionBehavior.
ManipulationDelta (
ManipulationDeltaEventArgs.IsInertial true) ,
,
ManipulationCompleted. ( Manipu
lationInertiaStarting , ManipulationCompleted
.)
,
, :
TranslationBehavior DesiredDisplacement, DesiredDeceleration, InitialVelocity
RotationBehavior DesiredRotation, DesiredDeceleration, InitialVelocity
ExpansionBehavior DesiredExpansion, DesiredDeceleration, InitialRadius, Ini
tialVelocity
DesiredDeceleration (
) DesiredDispla
cement ( ), DesiredRotation ( )
DesiredExpansion ( ).
,
. InitialVelocity InitialRadius
, .
ManipulationInertiaStarting,
ManipulationInertiaStartingEventArgs.InitialVelocities,
LinearVelocity, AngularVelocity ExpansionVelocity.
6.8 6.7 ,
.
220 6. : , ,
6.8. MainWindow.xaml.cs ManipulationDelta
ManipulationInertiaStarting ,
using
using
using
using
System;
System.Windows;
System.Windows.Input;
System.Windows.Media;
namespace ManipulationEvents
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
canvas.ManipulationDelta += Canvas_ManipulationDelta;
canvas.ManipulationInertiaStarting += Canvas_ManipulationInertiaStarting;
}
void Canvas_ManipulationInertiaStarting(object sender,
ManipulationInertiaStartingEventArgs e)
{
e.TranslationBehavior.DesiredDeceleration = 0.01;
e.RotationBehavior.DesiredDeceleration = 0.01;
e.ExpansionBehavior.DesiredDeceleration = 0.01;
}
void Canvas_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
MatrixTransform transform = photo.RenderTransform as MatrixTransform;
if (transform != null)
{
// ,
// MatrixTransform
Matrix matrix = transform.Matrix;
matrix.Translate(e.DeltaManipulation.Translation.X,
e.DeltaManipulation.Translation.Y);
matrix.RotateAt(e.DeltaManipulation.Rotation,
e.ManipulationOrigin.X, e.ManipulationOrigin.Y);
matrix.ScaleAt(e.DeltaManipulation.Scale.X,
e.DeltaManipulation.Scale.Y,
e.ManipulationOrigin.X, e.ManipulationOrigin.Y);
transform.Matrix = matrix;
e.Handled = true;
}
}
}
}
, ,
. Manipu
221
lationBoundaryFeedback, ,
,
.
WPF , -
, ,
iPhone. ,
ManipulationDelta ReportBoundaryFeedback
ManipulationDeltaEventArgs. Manipula
tionBoundaryFeedback, Window,
.
FAQ
ManipulationDeltaEventArgs Complete Cancel.
?
Complete ( , ).
Cancel ,
,
, , .
6.9
, .6.4.
Window:
<Window x:Class="SpinThePrizeWheel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Spin the Prize Wheel">
<Window.Background>
<LinearGradientBrush>
<GradientStop Color="White"/>
<GradientStop Color="Orange" Offset="1"/>
</LinearGradientBrush>
</Window.Background>
<Grid Name="grid" IsManipulationEnabled="True">
<Image Name="prizeWheel" RenderTransformOrigin="0.5,0.5"
Source="prizeWheel.png" Margin="0 30 0 0">
<Image.RenderTransform>
<RotateTransform/>
</Image.RenderTransform>
</Image>
<Image Source="arrow.png" VerticalAlignment="Top" Stretch="None"/>
</Grid>
</Window>
222 6. : , ,
.6.4. -
,
6.9. MainWindow.xaml.cs
using
using
using
using
System;
System.Windows;
System.Windows.Input;
System.Windows.Media;
namespace SpinThePrizeWheel
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
grid.ManipulationStarting += Grid_ManipulationStarting;
grid.ManipulationDelta += Grid_ManipulationDelta;
grid.ManipulationInertiaStarting += Grid_ManipulationInertiaStarting;
grid.ManipulationCompleted += Grid_ManipulationCompleted;
}
void Grid_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
{
//
e.Mode = ManipulationModes.Rotate;
}
void Grid_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
(prizeWheel.RenderTransform as RotateTransform).Angle +=
e.DeltaManipulation.Rotation;
}
223
6.9 ManipulationStarting ,
. ,
ManipulationDelta
, (
). ManipulationDelta
RotateTransform, Angle e.DeltaManipulation.Rotation. Angle
e.CumulativeManipulation.Rotation,
0, .
ManipulationInertiaStarting
,
. , ManipulationCompleted
.
ScrollViewer
PanningMode HorizontalOnly, VerticalOnly,
HorizontalFirst, VerticalFirst Both. ScrollViewer
PanningDeceleration PanningRatio.
TranslateTransform.
PanningMode None,
WPF ScrollViewer ,
.
224 6. : , ,
,
WPF ,
.
(, ListBoxItem
), ,
.
Cut (), Copy () Paste ().
:
MenuItem Menu, MenuItem ContextMenu, Button
ToolBar, ..
, Cut, Copy Paste,
. ,
( Click
Button, KeyDown Window ..). ,
,
(,
, ).
,
,
.
, WPF ,
.
(
)
, . ,
WPF; ,
Microsoft Foundation Class Library (MFC),
. , MFC,
WPF .
:
WPF .
225
(,
).
WPF
, ICommand (
System.Windows.Input),
:
Execute ,
CanExecute , true, ,
false,
CanExecuteChanged ,
CanExecute
Cut, Copy Paste, :
, ICommand; ,
( , );
Execute ( Can
Execute true) CanExecuteChanged
IsEnabled
. , .
, , Button, CheckBox MenuItem,
,
. Command ( ICom
mand). ,
Execute ( CanExecute true) ,
Click. , IsEnabled
, CanExecute,
CanExecuteChanged.
,
XAML.
. WPF ,
ICommand , Cut,
Copy Paste, , .
WPF
:
ApplicationCommands Close, Copy, Cut, Delete, Find, Help, New, Open, Paste, Print,
PrintPreview, Properties, Redo, Replace, Save, SaveAs, SelectAll, Stop, Undo .
ComponentCommands MoveDown, MoveLeft, MoveRight, MoveUp, ScrollByLine, Scroll
PageDown, ScrollPageLeft, ScrollPageRight, ScrollPageUp, SelectToEnd, SelectTo
Home, SelectToPageDown, SelectToPageUp .
226 6. : , ,
MediaCommands ChannelDown, ChannelUp, DecreaseVolume, FastForward, Increase
RoutedUICommand Text,
. (
RoutedUICommand
RoutedCommand.) , Help Text
Help ( ). ,
Content, :
helpButton.Content = ApplicationCommands.Help.Text;
Text RoutedUICommand
, WPF! , ,
Content ApplicationCommands.Help.Text,
,
. ,
, (, ),
, , .
,
- . Text
.
227
About , ,
. , ,
,
. .
CommandBinding
, ,
( ). ,
UIElement (ContentElement), CommandBin
dings, CommandBinding. Com
mandBinding Help Window
About. :
this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Help,
HelpExecuted, HelpCanExecute));
, HelpExecuted HelpCanExecute.
,
CanExecute Execute Help.
6.10 6.11 About,
Help Help,
XAML ( -
).
6.10. About Help
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="AboutDialog"
Title="About WPF Unleashed" SizeToContent="WidthAndHeight"
Background="OrangeRed">
<Window.CommandBindings>
<CommandBinding Command="Help"
CanExecute="HelpCanExecute" Executed="HelpExecuted"/>
</Window.CommandBindings>
<StackPanel>
<Label FontWeight="Bold" FontSize="20" Foreground="White">
WPF 4 Unleashed
</Label>
<Label> 2010 SAMS Publishing</Label>
<Label>Installed Chapters:</Label>
<ListBox>
<ListBoxItem>Chapter 1</ListBoxItem>
<ListBoxItem>Chapter 2</ListBoxItem>
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button MinWidth="75" Margin="10" Command="Help" Content=
"{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
<Button MinWidth="75" Margin="10">OK</Button>
</StackPanel>
<StatusBar>You have successfully registered this product.</StatusBar>
228 6. : , ,
</StackPanel>
</Window>
6.11. 6.10
using System.Windows;
using System.Windows.Input;
public partial class AboutDialog : Window
{
public AboutDialog()
{
InitializeComponent();
}
void HelpCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
void HelpExecuted(object sender, ExecutedRoutedEventArgs e)
{
System.Diagnostics.Process.Start("http://www.adamnathan.net/wpf");
}
}
Help About
Click. ,
, :
.
, F1.
About 6.10 F1
Help, Help! ,
Help
229
, .
, InputBindings
KeyBinding / MouseBinding. (
.) , F2
Help,
AboutDialog:
this.InputBindings.Add(
new KeyBinding(ApplicationCommands.Help, new KeyGesture(Key.F2)));
Help : F1 F2.
F1,
NotACommand:
this.InputBindings.Add(
new KeyBinding(ApplicationCommands.NotACommand, new KeyGesture(Key.F1)));
XAML-
:
<Window.InputBindings>
<KeyBinding Command="Help" Key="F2"/>
<KeyBinding Command="NotACommand" Key="F1"/>
</Window.InputBindings>
WPF
, ,
. TextBox,
Cut, Copy Paste ,
Undo Redo. , TextBox
Ctrl+X, Ctrl+C, Ctrl+V, Ctrl+Z Ctrl+Y,
.
XAML-:
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Orientation="Horizontal" Height="25">
<Button Command="Cut" CommandTarget="{Binding ElementName=textBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
<Button Command="Copy" CommandTarget="{Binding ElementName=textBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
<Button Command="Paste" CommandTarget="{Binding ElementName=textBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
<Button Command="Undo" CommandTarget="{Binding ElementName=textBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
<Button Command="Redo" CommandTarget="{Binding ElementName=textBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
230 6. : , ,
<TextBox x:Name="textBox" Width="200"/>
</StackPanel> 6
XAML
.xaml Internet Explorer
.
Content ,
Text .
CommandTarget TextBox (
, x:Reference,
WPF). TextBox, Button,
, TextBox .
XAML- , .6.5.
,
TextBox , ,
. Paste
,
, .
.6.5. , ,
TextBox
Button TextBox ,
.
WPF .
, (
) ,
.
WPF
, .
.NET,
.
, UIElement,
ContentElement (.
11) UIElement3D (. 16 ).
Windows
Windows
-
XAML-
XAML-
7.
WPF .
. -
WPF-. WPF
Windows,
, -,
,
, .
-
( ), ,
, Photo Gallery (),
Windows Live Photo Gallery.
, .
Windows
Windows .
. .7.1
Photo Gallery.
WPF Application Visual Studio
.
.NET, AssemblyInfo.*, Resources.*, Settings.*. WPF
App.xaml MainWindow.xaml (
). Application Window,
. ( Vi
sual Studio MainWindow.xaml Window1.xaml.)
232
7.
Window
Window ,
. WPF Window
Win32. WPF- Win32-
: ,
.. ( (Chrome)
, Minimize (),
Maximize () Close ().)
, Window Win32 ( ,
Form Windows Forms), .
Window,
Show, Hide ( , Visibility
Hidden Collapsed) Close.
, Window Control, Win32 ,
, , .
Window , Icon,
Title ( ) Windowstyle.
Left Top.
, WindowstartupLocation
CenterScreen CenterOwner. ,
, . ,
Topmost true,
, ShowInTaskbar false,
.
Window .
, Window,
Show.
. ,
, , ,
Windows
233
.
.
,
Owner ( Window) , ,
.
OwnedWindows.
, (, -
, ),
Activated Deactivated Window.
, Activate ( ,
SetForegroundWindow Win32 API).
, ShowAc
tivated false.
7.1 MainWindow Photo
Gallery.
7.1. MainWindow.xaml.cs,
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (MessageBox.Show("Are you sure you want to close Photo Gallery?",
"Annoying Prompt", MessageBoxButton.YesNo, MessageBoxImage.Question)
== MessageBoxResult.No)
e.Cancel = true;
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
//
...
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
//
...
234
7.
}
...
void exitMenu_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
...
}
MainWindow InitializeComponent,
Window, XAML-.
Closing, Closed Initialized.
OnEventName,
.
OnEventName, , WPF
. ,
, .
.NET Framework ,
.
InitializeComponent!
2 XAML
: InitializeComponent ,
XAML-,
. ,
XAML- . , Visual Studio
InitializeComponent,
.
Closing ,
, Close,
Alt+F4 ..
, true Cancel
CancelEventArgs ( Windows
Forms). OnClosing
, No, .
,
.
,
. ,
Closed ( ).
7.1 Closed ,
. , MainWindow
Initialized
Windows
235
. (
, .)
File
Exit, .
Application
,
. , ,
MainWindow, 7.1, Main:
public static void Main()
{
MainWindow window = new MainWindow();
window.Show();
}
. -, WPF (STA). ,
Main STAThread.
Show , (
ShowWindow Win32 API) .
Show Main, ,
. MainWindow
!
FAQ
?!
- COM!
, COM. ,
Win32 (
Windows Forms), WPF ,
.
, WPF (. 19
).
STA
WPF. STA-,
.
WPF , (, Dispat
cherObject) . ,
. ,
, (
). WPF
, .
236
7.
COM
, . Main STAThread
!
Main MainWindow,
,
MainWindow, ,
. ,
Win32: WM_PAINT, WM_MOUSEMOVE .. WPF
, Windows. Win32
,
. WPF System.Windows.
Application.
Application.Run
Application Run,
. Main
:
[STAThread]
public static void Main()
{
Application app = new Application();
MainWindow window = new MainWindow();
window.Show();
app.Run(window);
}
, Application StartupUri,
, :
[STAThread]
public static void Main()
{
Application app = new Application();
app.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
app.Run();
}
Main ,
MainWindow Show App
lication. : -, MainWindow
XAML-
(URI), -,
Run, Window. URI-
WPF 12 .
Windows
237
StartupUri
XAML. Visual Studio
WPF Application Application
App XAML- StartupUri
Window. Photo Gallery App.xaml
:
<Application x:Class="PhotoGallery.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml"/>
StartupUri
Uri.
App.xaml.cs
InitializeComponent:
using System.Windows;
namespace PhotoGallery
{
public partial class App : Application
{
public App()
{
InitializeComponent();
}
}
}
WPF- . , ,
Application,
.
FAQ
WPF- Main?
, Visual Studio WPF Application,
Main, ! ,
Main, , ,
.
App.xaml , Visual
Studio ApplicationDefinition.
Main. Photo Gallery
App.g.cs:
238
7.
[System.STAThreadAttribute()]
public static void Main() {
PhotoGallery.App app = new PhotoGallery.App();
app.InitializeComponent();
app.Run();
}
FAQ
WPF- ?
, Main, WPF-
Main .
. -, Application
XAML-, Main
.
System.Environment.GetCommandLineArgs,
, Main.
(
, - ) ,
Application
ApplicationDefinition, Page.
Main. , ,
Application Run
, App.g.cs.
Application
Application .
,
. ,
Application (, App, Visual Studio)
OnEventName,
Startup Exit, Activated Deactivated ( ,
Window, ,
), SessionEnding ,
, .
, ReasonSessionEnding.
Windows
239
, Application
Windows,
. ,
MainWindow.
, ,
.
Windows!
Window Application.Windows ,
, .
. , , Win
dows[2] !
( Run Application
), .
ShutdownMode
ShutdownMode. ,
, ( MainWin
dow), .
, Shutdown,
. ,
Windows (,
Windows).
Application - Properties.
ASP.NET, ,
( /
), .
Application
, Properties.
, Photo Gallery
:
myApplication.Properties["CurrentPhotoFilename"] = filename;
:
string filename = myApplication.Properties["CurrentPhotoFilename"] as string;
, , Object,
.
240
7.
Window,
,
Application. ,
Application.Current. , myApplication
Application.Current:
Application.Current.Properties["CurrentPhotoFilename"] = filename;
FAQ
WPF
(MDI)?
WPF MDI-,
Windows Forms. WPF-
, ,
(. 19). ! MDI-
, Aero Snap Windows 7 Flip 3D
Windows Vista. ,
( MDI),
WPF .
FAQ
WPF ,
?
WPF- :
( ) .
, C#:
bool mutexIsNew;
using (System.Threading.Mutex m =
new System.Threading.Mutex(true, uniqueName, out mutexIsNew))
{
if (mutexIsNew)
// , .
else
// . !
}
, uniqueName
!
(GUID) . ,
!
Windows
241
,
. .NET Framework
Microsoft.VisualBasic.ApplicationServices. WindowsFormsApp
licationBase, , ,
, WPF-. :
RPC-,
.
Application
Application
WPF-, .
Application,
, ,
.
Win32, WPF
Dispatcher System.Windows.Thre
ading, ,
Win32 API.
, Main Application.
Run, Dispatcher.Run. ( Application.Run Dispatcher.
Run !) -
. , Dispatcher.Run
, - Dispatcher.ExitAll
Frames (, Closed).
WPF-
. (
, .
,
.) ,
DispatcherObject
, . (
, Freezable.)
, WPF ,
. DispatcherObject Dispatcher ( Dispatcher).
Invoke ( ) BeginInvoke ( ).
,
242
7.
. Invoke
BeginInvoke Dispat
cherPriority, 10 , Send (
) SystemIdle (,
).
, Dispatcher.Run .
, ,
. ,
, ,
, . ,
Application,
. , Application.Windows
, , Application.
,
(
). WPF
.
,
.
, PNG-
, (,
GIF-) .
, WPF, ,
WPF. (
,
!) Office 2010,
, .
, .
Visual Studio 2010,
Add New Item ( ) Splash Screen
(WPF). ( Visual Studio 2008 SP1 http://
codeplex.com.) ,
SplashScreen;
. ! .7.2
Photo Gallery.
SplashScreen.
Visual Studio 2008 SP1 ,
. , ,
Windows
243
,
System.Windows.SplashScreen.
, .
Windows ( ),
,
, , .
. (
, ,
, .)
WPF
,
. , WPF
, Win32 API. ,
, .
, ShowDialog,
244
7.
. , Photo Gallery
PrintDialog :
void printMenu_Click(object sender, RoutedEventArgs e)
{
string filename = (pictureBox.SelectedItem as ListBoxItem).Tag as string;
Image image = new Image();
image.Source = new BitmapImage(new Uri(filename, UriKind.RelativeOrAbsolute));
PrintDialog pd = new PrintDialog();
if (pd.ShowDialog() == true) // true, false null
pd.PrintVisual(image, Path.GetFileName(filename) + " from Photo Gallery");
}
,
, Windows.
Windows, , , - ,
, Win
dows . ,
Windows7 : ;
, (Home
Group); ,
;
. , ,
, Windows7.
, ,
,
,
(Rename Photo) Photo Gallery (.7.3).
WPF ,
Window. Window,
.
Windows
245
.7.3.
Window ( )
, ShowDialog Show.
Show, ShowDialog (
, )
null ( bool? C#). Photo Gallery
RenameDialog:
void renameMenu_Click(object sender, RoutedEventArgs e)
{
string filename = (pictureBox.SelectedItem as ListBoxItem).Tag as string;
RenameDialog dialog = new RenameDialog(
Path.GetFileNameWithoutExtension(filename));
if (dialog.ShowDialog() == true) // true,
// false null
{
//
try
{
File.Move(filename, Path.Combine(Path.GetDirectoryName(filename),
dialog.NewFilename) + Path.GetExtension(filename));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Cannot Rename File", MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
}
,
( RenameDialog), , ShowDialog
true, , ,
, false .
, DialogResult
( bool?). DialogResult
. , OK
RenameDialog :
void okButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
246
7.
IsDefault true,
.
ShowDialog
,
, ShowDialog Window,
, Dispatcher.Run , Application.Run.
, WPF-
Application, :
[STAThread]
public static void Main()
{
MainWindow window = new MainWindow();
window.ShowDialog();
}
Windows
(
), ,
.
: .NET Framework.
,
, , Silver
light- XAML- (
).
Photo Gallery
, 7.2.
7.2. MainWindow.xaml.cs,
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
// ,
IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream stream =
new IsolatedStorageFileStream("myFile", FileMode.Create, f))
using (StreamWriter writer = new StreamWriter(stream))
{
foreach (TreeViewItem item in favoritesItem.Items)
Windows
247
writer.WriteLine(item.Tag as string);
}
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
//
IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream stream =
new IsolatedStorageFileStream("myFile", FileMode.OpenOrCreate, f))
using (StreamReader reader = new StreamReader(stream))
{
string line = reader.ReadLine();
while (line != null)
{
AddFavorite(line);
line = reader.ReadLine();
}
}
...
}
IsolatedStorageFile IsolatedStorageFileStream
System.IO.IsolatedStorage. ,
, Documents
() .
, Visual Studio Settings (
Properties\Settings.settings).
.
: ClickOnce
Windows
Windows, ,
, ,
Program Files ( , ),
,
, ,
. WPF-,
248
7.
Windows
249
, ClickOnce ,
, , ,
. ,
, ,
. , COM-
COM .
Windows
-,
Windows,
Windows, Windows Media Player , , Windows
Live Photo Gallery, Photo.
Photo Gallery, .7.1,
. WPF
.
,
, .
,
,
,
.
,
, -. ,
,
URI,
.
, , .
Photo Gallery,
.
, ..
, Navigation
Window Page.
WPF
Page. (Page , , Window.)
Page
: NavigationWindow Frame.
250
7.
, ,
, .
FAQ
NavigationWindow Frame?
: Navigati
onWindow , , Frame
HTML- FRAME IFRAME. NavigationWindow ,
Frame ( )
. Frame NavigationWindow
Frame. NavigationWindow
/, ,
ShowsNavigationUI,
Page. , NavigationWindow
ShowsNavigationUI, Frame NavigationUIVisibility,
Page.
MainPage.xaml,
NavigationWindow, Page, ,
MainWindow.xaml:
<Page x:Class="PhotoGallery.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Photo Gallery" Loaded="Page_Loaded">
... ...
</Page>
MainPage.xaml.cs
, MainWindow.xaml.cs.
MainPage.xaml.cs , ,
OnClosing OnClosed, ,
Page (
).
.7.4 , NavigationWindow Page Photo
Gallery
(). , ,
Windows
251
.7.4. NavigationWindow,
,
. Photo Gallery
,
, NavigationWindow. ,
Click NavigationWindow.GoBack,
Click NavigationWindow.GoForward.
WPF Page,
HTML- ( ,
)! WPF- HTML-
. , .
Page
NavigationService,
,
NavigationWindow Frame. NavigationService,
NavigationService.GetNavigationService,
Page. ,
NavigationService Page. ,
, ,
:
this.NavigationService.Title = "Main Photo Gallery Page";
252
7.
, :
this.NavigationService.Refresh();
Page ,
, WindowHeight, WindowWidth Win
dowTitle. , XAML Page.
,
( ), , (
-), .
:
Navigate
( Hyperlink)
Navigate
Navigate,
. ,
, URI:
//
PhotoPage nextPage = new PhotoPage();
this.NavigationService.Navigate(nextPage);
// URI
this.NavigationService.Navigate(new Uri("PhotoPage.xaml", UriKind.Relative));
Navigate
,
Navigate. Page,
Content:
this.NavigationService.Content = nextPage;
URI , Source:
this.NavigationService.Source = new Uri("PhotoPage.xaml", UriKind.Relative);
,
Navigate .
Windows
253
HTML-,
Navigate, URI. :
this.NavigationService.Navigate(new Uri("http://www.adamnathan.net/wpf"));
Hyperlink
WPF Hyperlink,
HTML. Hyperlink
TextBlock , HTML- A,
,
. Na
vigateUri Hyperlink ( href HTML). ,
XAML- , .7.5:
<TextBlock>
Click <Hyperlink NavigateUri="PhotoPage.xaml">here</Hyperlink> to view the photo.
</TextBlock>
.7.5. Hyperlink
, HTML
, Hyperlink HTML-
A. ,
WPF, HTML , .
,
Hyperlink, Hyperlink NavigateUri,
Click Navigate,
.
Hyperlink
HTML. , Frame ,
, TargetName Hyper
link .
Page ( HTML-, #),
URI # .
254
7.
FAQ
HTML- , WPF Page?
HTML ,
HREF ,
WPF Page. HTML WPF
, :
HREF -
Navigating, , Navigate
(Navigating
). HTML WPF
XAML
XAML- ( ,
Silverlight). .
,
, , .
, .7.4.
, .7.1.
7.1.
, GoBack GoForward
( CanGoBack
CanGoForward,
).
NavigationWindow , Frame
; JournalOwner
ship, :
OwnsJournal .
UsesParentJournal
, .
Windows
255
Automatic UsesParentJournal,
(NavigationWindow Frame),
OwnsJournal. .
,
. , NavigationUI
Visibility Hidden.
Page URI (,
Navigate Hyperlink)
Page, . , ,
,
(, Application.Proper
ties). ( Navigate, Page, ,
, , .)
Page,
JournalEntry.KeepAlive true.
Page ,
RemoveFromJournal true. ,
,
.
FAQ
,
?
,
.
,
StopLoading.
Refresh
. , Navigate, URI
, Navigating
NavigationMode.Refresh ,
.
256
7.
,
. ,
,
.
AddBackEntry,
CustomContentState. CustomContentState ,
, Replay.
,
. JournalEntryName,
.
Photo Gallery
, :
[Serializable]
class RotateState : CustomContentState
{
FrameworkElement element;
double rotation;
public RotateState(FrameworkElement element, double rotation)
{
this.element = element;
this.rotation = rotation;
}
public override string JournalEntryName
{
get { return "Rotate " + rotation + ""; }
}
public override void Replay(NavigationService navigationService,
NavigationMode mode)
{
//
element.LayoutTransform = new RotateTransform(rotation);
}
}
,
Navigate, Hyperlink ,
. ,
.
257
Windows
. 7.6 7.7
.
Initialized
Navigating
NavigationProgress
Loading
Initialized
Navigated
LoadCompleted
Loaded
.7.6. ,
Navigating
NavigationProgress
Loading
Unloaded
Initialized
Navigated
LoadCompleted
Loaded
.7.7. ,
NavigationProgress
Navigated. NavigationStopped.
LoadCompleted,
.
258
7.
.7.6 7.7 ,
( ).
Application,
.
HTML-!
WPF WPF
Page , WPF HTML HTML
WPF. HTML HTML
. HTML HTML
.
, , ,
- .
- HTML
URL . WPF
.
WPF , URL,
Navigate,
Object. ,
Page, Uri. -
( , , ..),
. :
int photoId = 10;
// Page
PhotoPage nextPage = new PhotoPage();
this.NavigationService.Navigate(nextPage, photoId);
// URI
this.NavigationService.Navigate(
new Uri("PhotoPage.xaml", UriKind.Relative), photoId);
,
LoadCompleted ExtraData
:
this.NavigationService.LoadCompleted += new
LoadCompletedEventHandler(container_LoadCompleted);
Windows
259
...
void container_LoadCompleted(object sender, NavigationEventArgs e)
{
if (e.ExtraData != null)
LoadPhoto((int)e.ExtraData);
}
Navigate, Page,
,
( ).
Photo Gallery :
int photoId = 10;
// Page
PhotoPage nextPage = new PhotoPage(photoId);
this.NavigationService.Navigate(nextPage);
, PhotoPage
:
public PhotoPage(int id)
{
LoadPhoto(id);
}
,
, PhotoPage ,
. !
Properties Application,
. :
// Page URI
Application.Properties["PhotoId"] = 10;
this.NavigationService.Navigate(...);
Navigate:
if (Application.Properties["PhotoId"] != null)
LoadPhoto((int)Application.Properties["PhotoId"]);
,
(
). , ,
.
PageFunction
,
, - ,
260
7.
( ,
). .
,
.
.7.8.
MainPage
SettingsPage
MainPage
.7.8. ,
. URI,
MainPage,
. ,
, ,
.
App
lication.Properties GoBack
.
, ,
( ),
, .
WPF
. .7.9.
MainPage
SettingsPage
.7.9.
PageFunction
PageFunction.
Page ( ),
.
Visual Studio PageFunction,
Page. ,
Add New Item Page Function (WPF):
261
<PageFunction
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Class="MyProject.PageFunction1"
x:TypeArguments="sys:String"
Title="PageFunction1">
<Grid>
</Grid>
</PageFunction>
TypeArguments. PageFunction
( PageFunction<T>),
- .
PageFunction . -
PageFunction
, ,
.
PageFunction Page,
, :
PageFunction1 nextPage = new PageFunction1<string>();
this.NavigationService.Navigate(nextPage);
Return PageFunction:
nextPage.Return += new ReturnEventHandler<string>(nextPage_Return);
...
void nextPage_Return(object sender, ReturnEventArgs<string> e)
{
string returnValue = e.Result;
}
, ReturnEventHandler ReturnEventArgs
-. Result
, ,
PageFunction ( ).
, PageFunction, ,
ReturnEventArgs OnReturn,
PageFunction:
OnReturn(new ReturnEventArgs<string>("the data"));
-
WPF
. ,
.
262
7.
,
.
, :
1. AllowsTransparency Window true.
, .
InvalidOperationException.)
2. Windowstyle Window None,
. (
AllowsTransparency="True" Inva
lidOperationException.)
3. Background Window Transparent.
.
4. , ,
DragMove Window.
, , ,
.
5. ,
. , ShowInTaskbar
false!
XAML- .
Close:
<Window x:Class="GadgetWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300"
AllowsTransparency="True" Windowstyle="None" Background="Transparent"
MouseLeftButtonDown="Window_MouseLeftButtonDown">
<Grid>
<Ellipse Fill="Red" Opacity="0.5" Margin="20">
<Ellipse.Effect>
<DropShadowEffect/>
</Ellipse.Effect>
</Ellipse>
<Button Margin="100" Click="Button_Click">Close</Button>
</Grid>
</Window>
DropShadowEffect 15 ;
.
:
using System.Windows;
using System.Windows.Input;
public partial class GadgetWindow : Window
{
XAML-
263
public GadgetWindow()
{
InitializeComponent();
}
void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.DragMove();
}
void Button_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
, MouseLeftButtonDown
Window.DragMove. DragMove
. .7.10 , .
.7.10. Window
()
XAML-
WPF ,
-. XAML-
(XAML Browser Applications XBAPs),
WPF- . XBAP-
, Silverlight
WPF. -
WPF-
.
264
7.
FAQ
XBAP-
?
. Silverlight, XBAP-
.NET Framework (3.0 ),
Windows Internet Explorer ( ,
ActiveX WebBrowser) Firefox (
.NET Framework 3.5 ). .NET Framework4.0
Firefox . (
3.5 .)
XBAP-
Windows ,
.NET, .
:
WPF .NET Framework.
.
-.
XAML .
, XBAP-? Visual Studio
:
1. , Visual Studio , ,
WPF Browser Application.
2. Page
.
3. .
Visual Studio, MSBuild,
(.
).
XAML-
, Visual Studio,
XBAP-. ,
:
<HostInBrowser>True</HostInBrowser>
<Install>False</Install>
<TargetZone>Internet</TargetZone>
XAML-
265
,
PresentationHost.exe, .
, ,
, ,
, , .
EXE- XML-:
.manifest ClickOnce-;
.xbap ClickOnce-
( , XBAP,
.application)
, , . XBAP- , , ClickOnce-
, , WPF
.
ClickOnce!
XBAP- ClickOnce,
, .
ClickOnce-
.
, . (
, ClickOnce ,
Documents .)
, , ,
,
! Visual Studio
(- AssemblyVersion("1.0.*") Assembly
Info), ,
.
,
, ,
mage.exe Windows SDK.
mage -cc. SDK ,
rundll32 %windir%\system32\dfshim.dll CleanOnlineAppCache
WPF-
,
XAML- . WPF-
. XBAP- ,
,
266
7.
API. ,
Photo Gallery XBAP, , , ,
( ):
// ! !
AddFavorite(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
.NET Framework
, FileIO
Permission, . (
, ,
,
.)
, ,
, . ,
,
,
Window. ( Popup
, Page.)
, ,
,
.
. , WPF XBAP-
WebBrowser,
Firefox.
XBAP- ,
, ,
.
BrowserInteropHelper.IsBrowserHosted
System.Windows.Interop.
,
.
, ( 512
), -.
(
). Microsoft.Win32.OpenFileDialog:
string fileContents = null;
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == true) // true, false null
{
XAML-
267
XBAP Windows
( ).
URL- HTML-,
XBAP-, URL ( )
BrowserInteropHelper.Source.
cookie ,
Application.GetCookie.
FAQ
?
, .NET:
AllowPartiallyTrustedCallers
( ,
), XBAP-
API.
, AllowPartiallyTrustedCallers
.
, -
, .
, , , .
FAQ
XBAP- ?
,
, ,
XBAP- . ,
:
1. ClickOnce- (app.manifest) Unrestric
ted="true" XML- PermissionSet, :
<PermissionSet class="System.Security.PermissionSet" version="1"
ID="Custom" SameSite="site" Unrestricted="true"/>
268
7.
2. ( .csproj .vbproj)
<TargetZone>Internet</TargetZone>
:
<TargetZone>Custom</TargetZone>
Visual Studio
Security ().
XBAP-
.
, (,
, ) .
Page XBAP- Navigation
Window. Internet Explorer 6 Firefox
. , XBAP-
. , ,
. ,
false ShowsNavigationUI Page.
, Internet Explorer 7 Navi
gationWindow ,
. ,
, WPF,
, , .
Internet Explorer 7 ( )
Page . XBAP-
HTML- IFRAME, ,
false ShowsNavigationUI WPF- Page.
XAML-
269
XBAP- ,
, URL-,
( Internet Explorer). ,
ClickOnce-,
, , , , XBAP-
- . (,
, !)
FAQ
XBAP ,
. ?
.
Windows, Internet Explorer .NET Framework
WPF ,
XBAP, . , .NET Framework
(sandbox) , Internet Explorer.
, WPF
(, )
,
.
ClickOnce
, ,
,
, .
XBAP-,
,
.
, Visual Studio
. ,
PublishApplication Files (
), .
270
7.
.
System.Deployment.Application ( Sys
tem.Deployment.dll) API.
7.3 ,
.
, Page1,
7.3. (
XAML- ,
.) Page1 ,
MyGroup, Page2 (
- ).
7.3. ClickOnce
using
using
using
using
System;
System.Windows.Controls;
System.Windows.Threading;
System.Deployment.Application;
XAML-
271
// Page2 .
// DispatcherOperationCallback.
private object GotoPage2(object o)
{
return NavigationService.Navigate(new Uri("Page2.xaml", UriKind.Relative));
}
}
,
( ),
ApplicationDeployment.IsNetworkDeployed, ,
. ,
,
Page2. ,
DownloadFileGroupAsync.
DownloadFileGroupCompleted ,
. ApplicationDeployment
,
.
XAML-
.NET Framework 3.0 , Internet
Explorer WPF
XAML- , HTML-.
HTML XAML,
, , .. ,
: XAML-
Windows. ,
.
, XAML-
(. 13 ). .7.11
Photo Gallery XAML-.
, -,
.
,
XAML, HTML-
, XAML,
.
, ".NET
CLR 3.0". , , .
Silverlight .
272
7.
HTML XAML,
XAML- IFRAME
HTML-.
WPF ,
Windows,
, , .
Photo Gallery, (
http://informit.com/title/9780672331190), ,
Windows, -
.
.
.NET Framework. , Win
dows Vista WPF3.0, Windows7
WPF3.5. Windows, ,
WPF4 .
,
.NET Framework.
Aero Glass
TaskDialog
8.
Windows 7
Windows ,
, Windows7 . Windows
Vista, Windows7
, .
,
.
, WPF-
Windows7 :
, Windows Vista,
Windows7:
Aero Glass
TaskDialog
Windows7 .
, ,
. .8.1 Internet Explorer.
,
, .
.8.2
Photo Gallery :
. (
, .)
274
8. Windows 7
.8.2. ,
Photo Gallery
WPF4 System.Windows.Shell.JumpList,
XAML! ,
WPF,
.
,
JumpList.JumpList Appli
cation, JumpList.
JumpList.SetJumpList. JumpList
,
Windows Apply .
JumpList JumpItems,
: JumpTask JumpPath;
JumpItem.
275
JumpTask
, JumpTask
, Start InPrivate Browsing ( InPrivate) Open
new tab ( ) .8.1. ,
JumpTask (
). -
, , .
8.1 JumpTask
App.xaml, Photo Gallery
.
.8.3. , (,
) ,
, .
8.1. App.xaml
JumpTask
<Application x:Class="PhotoGallery.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<JumpList.JumpList>
<JumpList>
<JumpTask Title="Launch another instance"
Description="Launches another instance of this program."/>
<JumpTask Title="Task #1" Arguments="-task1"
Description="Performs task #1."/>
<JumpTask Title="Task #2" Arguments="-task2"
Description="Performs task #2."/>
</JumpList>
</JumpList.JumpList>
</Application>
.8.3. JumpTask
JumpTask Title ,
, Description,
276
8. Windows 7
. , Jump
Task Photo Gallery.
, ,
. JumpTask
Photo Gallery
,
- . Photo Gallery
Environment.CommandLine .
,
, -
. ,
,
( ),
, .
,
,
. .8.4 , , 8.1,
.
.8.4.
, .8.3
277
Visual Studio !
Visual Studio
vshost32.exe, .8.5. ,
, (
vshost32.exe, ).
JumpPath, ,
. , Enable the Visual Studio
hosting process ( Visual Studio) Debug ()
.
!
,
. , ,
, .
, ,
, .
JumpTask
JumpTask
, .
8.2, .8.6 .
278
8. Windows 7
8.2. App.xaml
JumpTask
<Application x:Class="PhotoGallery.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<JumpList.JumpList>
<JumpList>
<JumpTask Title="Magnifier"
Description="Open the Windows Magnifier."
ApplicationPath="%WINDIR%\system32\magnify.exe"/>
<JumpTask Title="Calculator"
Description="Open the Windows Calculator."
ApplicationPath="%WINDIR%\system32\calc.exe"
IconResourcePath="%WINDIR%\system32\calc.exe"/>
<JumpTask Title="Notepad"
Description="Open Notepad."
ApplicationPath="%WINDIR%\system32\notepad.exe"
IconResourcePath="%WINDIR%\system32\notepad.exe"
WorkingDirectory="%HOMEDRIVE%%HOMEPATH%"/>
<JumpTask Title="Internet Explorer (No Add-Ons)"
Description="Start without ActiveX controls or extensions."
ApplicationPath="%PROGRAMFILES%\Internet Explorer\iexplore.exe"
IconResourcePath="%PROGRAMFILES%\Internet Explorer\iexplore.exe"
WorkingDirectory="%HOMEDRIVE%%HOMEPATH%"
IconResourceIndex="6" Arguments="-extoff"/>
</JumpList>
</JumpList.JumpList>
</Application>
.8.6. JumpTask
JumpTask , .
ApplicationPath
279
magnify.exe. , ApplicationPath
, XAML,
.
JumpTask IconResourcePath,
. Win32, EXE-
DLL-. ( .ico,
, ,
XAML- .) EXE-,
.
IconResourcePath null, JumpTask,
- .
JumpTask Photo Gallery.
%WINDIR%\System32\shell32.dll %WINDIR%\System32\imageres.dll
,
JumpTask. , Windows ,
.
JumpTask WorkingDirectory,
( ). ,
ApplicationPath IconResourcePath,
.
JumpTask Arguments,
Internet Explorer ,
IconResourceIndex . .8.6
,
e. EXE- DLL-
. IconResourceIndex , 0,
(, Windows).
EXE- DLL- ,
, IconResourceIndex, .
, , .8.5.
JumpTask
, IconResourceIndex -1.
, IconResourcePath .
280
8. Windows 7
JumpTask ,
JumpTask,
. .8.7 , , <JumpTask/>
8.2.
.8.7.
JumpTask
CustomCategory
JumpTask, JumpItem. ,
,
Tasks ().
8.3 One
Two. .8.8.
8.3. App.xaml CustomCategory
<Application x:Class="PhotoGallery.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<JumpList.JumpList>
<JumpList>
<JumpTask Title="Magnifier" CustomCategory="One"
Description="Open the Windows Magnifier."
ApplicationPath="%WINDIR%\system32\magnify.exe"/>
<JumpTask Title="Calculator" CustomCategory="Two"
Description="Open the Windows Calculator."
281
ApplicationPath="%WINDIR%\system32\calc.exe"
IconResourcePath="%WINDIR%\system32\calc.exe"/>
<JumpTask Title="Notepad" CustomCategory="Two"
Description="Open Notepad."
ApplicationPath="%WINDIR%\system32\notepad.exe"
IconResourcePath="%WINDIR%\system32\notepad.exe"
WorkingDirectory="%HOMEDRIVE%%HOMEPATH%"/>
<JumpTask Title="Internet Explorer (No Add-Ons)"
Description="Start without ActiveX controls or extensions."
ApplicationPath="%PROGRAMFILES%\Internet Explorer\iexplore.exe"
IconResourcePath="%PROGRAMFILES%\Internet Explorer\iexplore.exe"
WorkingDirectory="%HOMEDRIVE%%HOMEPATH%"
IconResourceIndex="6" Arguments="-extoff"/>
</JumpList>
</JumpList.JumpList>
</Application>
.8.8.
JumpTask , Arguments!
- Windows7 .
, .
, .
, ,
, ,
.
, ,
(
).
282
8. Windows 7
Pinned ().
, .8.9.
.8.9. JumpTask
!
JumpTask, ,
JumpItems. JumpTask
, ! Two
.8.8 8.9 One.
JumpPath
JumpTask , JumpPath ,
- .
JumpPath,
Windows .
,
JPG- (
, Windows,
(Open WithChoose
Default Program).
8.4 8.3
JumpTask JumpPath (
, JumpItem).
C:
JPG-, ,
283
.8.10.
, , .8.8.
8.4. App.xaml JumpPath 8.3
<Application x:Class="PhotoGallery.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<JumpList.JumpList>
<JumpList>
<JumpPath Path="C:\Users\Adam\Pictures\DSC06397.jpg"
CustomCategory="Photos"/>
<JumpTask Title="Magnifier" CustomCategory="One"
Description="Open the Windows Magnifier."
ApplicationPath="%WINDIR%\system32\magnify.exe"/>
...
</JumpList>
</JumpList.JumpList>
</Application>
JumpPath Tasks,
. ,
CustomCategory ( JumpItem).
,
.
DSC06397.jpg,
-,
Path. ,
, JumpPath 8.4
JumpTask:
284
8. Windows 7
<JumpTask Title="DSC06397.jpg"
Arguments="C:\Users\Adam\Pictures\DSC06397.jpg"
Description="DSC06397 (C:\Users\Adam\My Pictures)"
CustomCategory="Photos"/>
, ,
, JumpTask.
Path JumpPath
!
8.4 JPG- . ,
, .
JumpPath ,
(
).
JumpPath
JumpPath. ,
:
.
,
ShowRecentCategory / ShowFrequentCategory
JumpList true.
. Windows ,
(File Open)
(
, Windows
JumpPath).
-
(, ,
), JumpList.AddToRecentCategory.
, ,
JumpPath JumpTask. AddToFrequentCate
gory; ,
.
8.4
, .8.11.
<JumpList ShowFrequentCategory="True" ShowRecentCategory="True">
<JumpPath Path="C:\Users\Adam\Pictures\DSC06397.jpg"
285
CustomCategory="Photos"/>
<JumpTask Title="Magnifier" CustomCategory="One"
Description="Open the Windows Magnifier."
ApplicationPath="%WINDIR%\system32\magnify.exe"/>
...
</JumpList>
,
- , . .8.1,
Internet Explorer
(Frequent),
(Recent). (Windows7 Recent
, .)
, Windows
JumpPath JumpItems ,
.
, JumpItemsRejected JumpList.
JumpItemsRejected
, JumpList,
286
8. Windows 7
.
JumpList, XAML-,
XAML. JumpList ,
Apply.
JumpItemsRejectedEventArgs, ,
JumpItem,
JumpItemRejectionReason, :
NoRegisteredHandler
.
InvalidItem ( Windows,
Windows7).
RemovedByUser .
None .
, ,
JumpItemsRemovedByUser,
JumpItem. ,
, , , -
JumpTask.
.
JumpItemsRejected
JumpItemsRemovedByUser
,
JumpList.Apply, , WPF
Shell Win32 API. Windows Shell
, .
(, WPF) . Win
dows , ;
, . , Windows
, ,
,
.
Apply JumpList ,
JumpTask JumpPath,
. ,
, ,
. Apply WPF
JumpList , .
( ) Apply, WPF
,
.
287
WPF4 Window TaskbarItemInfo (
System.Windows.Shell.TaskbarItemInfo),
. ,
,
Description TaskbarItemInfo :
<Window ...>
<Window.TaskbarItemInfo>
<TaskbarItemInfo Description="Custom tooltip"/>
</Window.TaskbarItemInfo>
...
</Window>
C#:
public MainWindow()
{
...
this.TaskbarItemInfo = new TaskbarItemInfo();
this.TaskbarItemInfo.Description = "Custom tooltip";
}
.8.12 . , TaskbarItemInfo
.
.8.12. ,
TaskbarItemInfo.Description
. ,
, .
Windows, Internet Explorer.
, .
288
8. Windows 7
,
TaskbarItemInfo: ProgressValue ProgressState. ProgressValue
double 0 (0%) 1 (100%),
. ProgressState
, TaskbarItemProgressState:
Normal .
Paused .
Error .
Indeterminate ,
, Progress
Value.
None . .
, . ,
, . ,
. ,
, ProgressState Paused.
Indeterminate ProgressState ,
, .
ProgressValue ,
.
ProgressState ProgressValue ,
. .8.13
ProgressState , ProgressValue
.85.
Paused
Normal
Indeterminate
Error
None
.8.13. ProgressState,
,
,
. TaskbarItemInfo
Overlay ImageSource (
).
.8.14 , :
289
<Window ...>
<Window.TaskbarItemInfo>
<TaskbarItemInfo Overlay="overlay.png"/>
</Window.TaskbarItemInfo>
...
</Window>
overlay.png
.8.14.
,
, .
, Taskbar
ItemInfo , Windows,
Windows7.
.
Overlay null,
.
Overlay
.
!
,
,
. TaskbarItemInfo
. ThumbnailClipMargin ( Thickness),
.
.8.15 .
Photo Gallery ThumbnailClipMargin
( )
.
290
8. Windows 7
.8.15. ,
, TaskbarItemInfo,
, Windows Media Player:
/, , .
ThumbButtonInfos ThumbButtonInfo.
ThumbButtonInfo WPF UIElement,
, .
, ImageSource.
ThumbButtonInfo ImageSource, ,
Description, , Click. (
, Button, Click .)
, ThumbButtonInfo Command
CommandTarget CommandParameter,
.
ThumbButtonInfo Visibility,
. ( ,
, WPF .)
: IsEnabled, IsInteractive, IsBackgroundVisible DismissWhenClicked;
, , true. (background),
IsBackgroundVisible,
, .
.8.16
Photo Gallery:
<Window ...>
<Window.TaskbarItemInfo>
291
<TaskbarItemInfo>
<TaskbarItemInfo.ThumbButtonInfos>
<ThumbButtonInfo Description="Previous" Click="..."
ImageSource="Images\previousSmall.gif"/>
<ThumbButtonInfo Description="Slideshow" Click="..."
ImageSource="Images\slideshowSmall.gif"/>
<ThumbButtonInfo Description="Next" Click="..."
ImageSource="Images\nextSmall.gif"/>
<ThumbButtonInfo Description="Undo" Click="..."
ImageSource="Images\counterclockwiseSmall.gif"/>
<ThumbButtonInfo Description="Redo" Click="..."
ImageSource="Images\clockwiseSmall.gif"/>
<ThumbButtonInfo Description="Delete" Click="..."
ImageSource="Images\deleteSmall.gif"/>
</TaskbarItemInfo.ThumbButtonInfos>
</TaskbarItemInfo>
</Window.TaskbarItemInfo>
...
</Window>
.8.16.
ThumbButtonInfo!
,
ThumbButtonInfos .
,
Visibility Collapsed (
). ,
, ,
,
Visibility.
292
8. Windows 7
FAQ
?
. Windows
.
Aero Glass
Aero Glass , ,
. Win
dows Vista. WPF-,
DwmExtendFrameIntoClientArea Win32 API. ( Dwm
Desktop Window Manager.) Window
( .8.17)
,
( .8.18).
WPF-,
.
.8.17. Window
Aero Glass
293
.8.18.
294
8. Windows 7
[DllImport("dwmapi.dll", PreserveSig=false)]
static extern void DwmExtendFrameIntoClientArea(
IntPtr hWnd, ref MARGINS pMarInset);
[DllImport("dwmapi.dll", PreserveSig=false)]
static extern bool DwmIsCompositionEnabled();
public static bool ExtendGlassFrame(Window window, Thickness margin)
{
if (!DwmIsCompositionEnabled())
return false;
IntPtr hwnd = new WindowInteropHelper(window).Handle;
if (hwnd == IntPtr.Zero)
throw new InvalidOperationException(
"The Window must be shown before extending glass.");
// WPF, Win32
window.Background = Brushes.Transparent;
HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor =
Colors.Transparent;
MARGINS margins = new MARGINS(margin);
DwmExtendFrameIntoClientArea(hwnd, ref margins);
return true;
}
}
GlassHelper.ExtendGlassFrame Window
Thickness; ,
,
. ( ,
1.) ,
( Aero Glass),
Thickness MARGINS,
DwmExtendFrameIntoClientArea, ,
HWND. Background Window
Transparent, .
. 19
.
WPF- Window GlassHelper.Extend
GlassFrame :
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
// SourceInitialized:
GlassHelper.ExtendGlassFrame(this, new Thickness(-1));
// ,
// ,
Aero Glass
295
,
, ,
.
, Remote Desktop (
).
, Win32 WM_DWMCOMPOSI
TIONCHANGED. ,
19.
.8.19 Photo
Gallery.
296
8. Windows 7
TaskDialog
MessageBox ,
.
, Windows Vista ,
MessageBox TaskDialog, .
Windows
.
,
TaskDialog Win32 API. Aero Glass,
PInvoke. 8.6
PInvoke TaskDialog .
8.6. TaskDialog C#
[DllImport("comctl32.dll", PreserveSig=false, CharSet=CharSet.Unicode)]
static extern TaskDialogResult TaskDialog(IntPtr hwndParent, IntPtr hInstance,
string title, string mainInstruction,string content,
TaskDialogButtons buttons, TaskDialogIcon icon);
enum TaskDialogResult
{
Ok=1,
Cancel=2,
Retry=4,
Yes=6,
No=7,
Close=8
}
[Flags]
enum TaskDialogButtons
{
Ok = 0x0001,
Yes = 0x0002,
No = 0x0004,
Cancel = 0x0008,
Retry = 0x0010,
Close = 0x0020
}
enum TaskDialogIcon
{
Warning = 65535,
Error = 65534,
Information = 65533,
Shield = 65532
}
TaskDialog
297
MessageBox, TaskDialog
, . ,
. .8.20 8.21
MessageBox TaskDialog,
:
// MessageBox
result = MessageBox.Show("Are you sure you want to delete '" + filename + "'?",
"Delete Picture", MessageBoxButton.YesNo, MessageBoxImage.Warning);
// TaskDialog
result = TaskDialog(new System.Windows.Interop.WindowInteropHelper(this).Handle,
IntPtr.Zero, "Delete Picture",
"Are you sure you want to delete '" + filename + "'?",
"This will delete the picture permanently, rather than sending it
to the Recycle Bin.",
TaskDialogButtons.Yes | TaskDialogButtons.No,
TaskDialogIcon.Warning);
.8.21. TaskDialog
298
8. Windows 7
Win32
( RT_MANIFEST ID, 1),
. Visual Studio,
.
, TaskDialog
"Unable to find an entry point named 'TaskDialog' in DLL
'comctl32.dll'". ,
TaskDialog.
Win32, MessageBox,
.
TaskDialog
TaskDialogIndirect. Windows SDK
Win32 .NET.
PInvoke Win32 API
http://pinvoke.net.
299
, Windows 7,
, Windows Vista. , WPF
XAML
.NET- . ,
Windows Vista, PInvoke,
Win32 API.
,
.
Windows7,
WPF. ,
Win32 API Windows7 (Windows Vista).
,
,
Windows API Code Pack http://code.msdn.micro
soft.com/WindowsAPICodePack. ,
Windows7 Windows Vista
.
,
.
WPF4,
Windows7,
WPF Shell Integration Library,
http://code.msdn.microsoft.com/WPFShell.
.NET Framework 3.5
System.Windows.Shell WPF4. API
(, 3.5 Taskbar
ItemInfo , ),
WPF.
, Win
dows, , ,
(, ,
).
300
8. Windows 7
System.Windows.Shell WPF
Windows. Windows Vista,
, JumpList, TaskbarItemInfo .,
, .
PInvoke,
Windows
. .NET
System.Environment.OSVersion. :
if (System.Environment.OSVersion.Version.Major >= 6)
// Windows Vista , TaskDialog
else
// Windows Vista, MessageBox
III
III.
9
10
11 ,
9.
,
. Win
dows Presentation Foundation .
.
,
.
,
WPF Aero, Windows7 Windows Vista.
WPF ,
. , WPF DLL- ,
Windows:
Aero ( Windows7 Windows Vista)
Luna ( Windows XP)
Royale ( Windows XP Media Center Edition 2005 Win
dows XP Tablet PC Edition 2005)
Classic ( Windows2000 )
.9.1 WPF
Windows. WPF ,
Zune, Microsoft 2006, Classic.
Aero
Luna
Royale
.9.1. WPF
Classic
304
9.
. ,
( )
, 14 , ,
.
WPF
, :
( )
(10
)
(11 ,
)
(11)
,
, .
, System.Windows.Controls.ContentControl,
Content Object, (
Button, 2
XAML).
, , ,
. .
Content, ContentControl
HasContent. false, Content null, true
.
:
FAQ
ContentControl HasContent?
Content==null , HasContent==false!
WPF API, ,
.NET API! C# HasContent .
XAML . ,
,
, HasContent true.
305
Window, 7
,
. Content -
Panel, Grid,
.
Content
Content , ,
, , ,
, Hashtable TimeZone. :
, UIElement,
OnRender . ,
(. 13 ),
.
ToString -
TextBlock.
, ,
. WPF Button, .9.1,
.
, ,
( , WPF) .
, ,
.
ButtonBase, .
ButtonBase Click ,
. Windows,
Enter , .
ButtonBase IsPressed ,
- ,
( ,
).
ButtonBase ClickMode.
, ClickMode,
, Click.
: Release ( ), Press Hover. ClickMode
306
9.
,
,
- . ,
, .
Click
Click, ButtonBase
, MouseLeftButtonDown MouseLeftButtonUp. Click
Mode Release Press,
, ButtonBase, ButtonBase
MouseButtonEventArgs.Handled true. Hover
MouseEnter MouseLeave.
,
ButtonBase, Preview- (PreviewMou
seLeftButtonDown, PreviewMouseLeftButtonUp ..),
Add
Handler, .
ButtonBase
, .
Button
RepeatButton
ToggleButton
CheckBox
RadioButton
ButtonBase ,
, Calendar DataGrid.
Button
Button WPF , ButtonBase,
: .
. ,
( Window, ShowDialog),
Button.IsCancel true,
DialogResult false.
Button.IsDefault true, Enter
, .
307
FAQ
IsDefault IsDefaulted Button?
IsDefault ,
. , IsDefaulted
( ) .
, ,
Enter . , IsDe
faulted true : IsDefault
true , TextBox
( AcceptsReturn false).
Enter , TextBox.
FAQ
?
Button, WPF,
System.Windows.Automation.Peers,
: ButtonAutomationPeer.
myButton :
ButtonAutomationPeer bap = new ButtonAutomationPeer(myButton);
IInvokeProvider iip = bap.GetPattern(PatternInterface.Invoke)
as IInvokeProvider;
iip.Invoke(); //
,
.
RepeatButton
RepeatButton , Button,
Click , . ( ,
,
ButtonBase.) Click
Delay Interval, SystemParameters.KeyboardDelay
SystemParameters.KeyboardSpeed . RepeatButton
, Button (. .9.1).
RepeatButton ,
( ) ,
. ,
,
308
9.
. :
( WPF),
, , RepeatButton
. RepeatButton Sys
tem.Windows.Controls.Primitives, , ,
, .
ToggleButton
ToggleButton ,
(
). IsChecked
true, false. ToggleButton
, Button RepeatButton.
ToggleButton IsThreeState; true,
IsChecked : true, false null.
IsChecked Nullable<Boolean> (bool?
C#). IsChe
cked true, null, false ..
, , Preview , IsChecked
, OnToggle
ToggleButton, .
IsChecked, ToggleButton
IsChecked: Checked true, Unchecked false
Indeterminate null. ,
IsCheckedChanged, , ,
.
RepeatButton, ToggleButton System.
Windows.Controls.Primitives, WPF ,
.
ToolBar,
10.
CheckBox
CheckBox, . 9.2,
. ,
? - ,
CheckBox WPF:
,
( ).
.
: .
309
,
.
? , CheckBox ,
ToggleButton ! CheckBox
ToggleButton ,
, .9.2.
CheckBox
CheckBox ,
ToggleButton,
Win32. CheckBox , (+)
, () ! , ,
IsThreeState false.
RadioButton
RadioButton , ToggleButton.
.
RadioButton ,
.
- RadioButton
.
-
RadioButton, ; .
, RadioButton
, . . 9.3
RadioButton.
RadioButton (IsThree
State=true IsChecked=null) ,
;
. RadioButton
, -
, .
310
9.
RadioButton
. ,
, .
, :
<StackPanel>
<RadioButton>Option 1</RadioButton>
<RadioButton>Option 2</RadioButton>
<RadioButton>Option 3</RadioButton>
</StackPanel>
.
- ,
GroupName,
. GroupName
( , ).
, ,
:
<StackPanel>
<StackPanel>
<RadioButton GroupName="A">Option 1</RadioButton>
<RadioButton GroupName="A">Option 2</RadioButton>
</StackPanel>
<StackPanel>
<RadioButton GroupName="A">Option 3</RadioButton>
</StackPanel>
</StackPanel>
:
<StackPanel>
<RadioButton
<RadioButton
<RadioButton
<RadioButton
</StackPanel>
GroupName="A">Option 1</RadioButton>
GroupName="A">Option 2</RadioButton>
GroupName="B">A Different Option 1</RadioButton>
GroupName="B">A Different Option 2</RadioButton>
, -
, , ,
!
311
WPF ,
, , .
. :
Label
ToolTip
Frame
Label
Label () , ,
, . ,
WPF, Content
Button, Menu ..,
- .
WPF ,
TextBlock.
. ,
Alt . ,
,
. ( Windows
), .
,
Target ( UIElement).
, Label Button,
, ,
, _Open Save_As. (Win32 Windows Forms
[&],
XML.) ,
, , __Open Save __As.
TextBox. , XAML-
TextBox Alt+U:
<Label Target="userNameBox">_User Name:</Label>
<TextBox x:Name="userNameBox"/>
Target
NameReferenceConverter, 2. C#
312
9.
TextBox (,
userNameLabel):
userNameLabel.Target = userNameBox;
ToolTip
ToolTip ( )
, ,
, ,
. .9.4
ToolTip,
XAML-:
<Button>
OK
<Button.ToolTip>
<ToolTip>
Clicking this will submit your request.
</ToolTip>
</Button.ToolTip>
</Button>
ToolTip UIElement
. ToolTip (
FrameworkElement FrameworkContentElement).
ToolTip , ToolTip
! Object,
, ToolTip, ToolTip
.
XAML-, .9.4, :
<Button>
OK
<Button.ToolTip>
Clicking this will submit your request.
</Button.ToolTip>
</Button>
:
<Button Content="OK" ToolTip="Clicking this will submit your request."/>
313
WPF ToolTip
! 9.1 ,
(ScreenTip) Microsoft Office.
.9.5.
9.1.
Microsoft Office ScreenTip
<CheckBox>
CheckBox
<CheckBox.ToolTip>
<StackPanel>
<Label FontWeight="Bold" Background="Blue" Foreground="White">
The CheckBox
</Label>
<TextBlock Padding="10" TextWrapping="WrapWithOverflow" Width="200">
CheckBox is a familiar control. But in WPF, it's not much
more than a ToggleButton styled differently!
</TextBlock>
<Line Stroke="Black" StrokeThickness="1" X2="200"/>
<StackPanel Orientation="Horizontal">
<Image Margin="2" Source="help.gif"/>
<Label FontWeight="Bold">Press F1 for more help.</Label>
</StackPanel>
</StackPanel>
</CheckBox.ToolTip>
</CheckBox>
.9.5. WPF
Microsoft Office
ToolTip ,
, -
.
ToolTip Open Closed ,
- .
, : ,
, ,
. , ToolTip
314
9.
, , .
ToolTipService.
ToolTipService ,
, ToolTip (
ToolTip).
ToolTip ( ,
), . , ShowDuration
, ,
, Initial
ShowDelay
. , ToolTip,
ShowDuration :
<Button ToolTipService.ShowDuration="3000">
...
</Button>
FAQ
,
?
ShowOnDisabled
ToolTipService.
XAML :
<Button ToolTipService.ShowOnDisabled="True">
...
</Button>
C# ,
:
ToolTipService.SetShowOnDisabled(myButton, true);
FAQ
?
false IsOpen.
Frame
Frame ,
.
.
315
, (
WPF) .
Frame WPF HTML-.
HTML, Frame
, WPF-, HTML-
. Frame Source System.Uri,
HTML ( XAML). :
<Frame Source="http://www.adamnathan.net"/>
Frame -
NavigationFailed,
, NavigationFailedEventArgs.Handled
true. (, WebExcep
tion) . NavigationFailedEventArgs,
,
.
7 , Frame
,
HTML-, XAML-. Frame
ActiveX Microsoft Web Browser
WPF WebBrowser.
, Frame HTML-,
,
WPF (- , HTML
Win32). , HTML- WPF-
, ,
Opacity .. Frame
HTML;
316
9.
URL- . ,
HTML-, WPF
WebBrowser.
Content Frame
Frame Content,
XAML. ,
Frame XAML . Con
tent :
<Frame>
<Frame.Content>
...
</Frame.Content>
</Frame>
Frame ContentProper
tyAttribute, [ContentProperty("Content")]
ContentControl. ?
WPF, ,
Content Frame,
Source,
. , Frame
,
NavigationWindow, 7. ,
Source Content, Content.
(
, ..).
,
.
ContentControl, HeaderedContentControl
Header Object.
GroupBox
GroupBox
. .9.6 GroupBox,
CheckBox. XAML-:
<GroupBox Header="Grammar">
<StackPanel>
317
, GroupBox ,
,
. GroupBox
- ,
. , StackPanel.
Content, Header ,
, UIElement,
. , Header Button (. ),
, .9.7:
<GroupBox>
<GroupBox.Header>
<Button>Grammar</Button>
</GroupBox.Header>
<StackPanel>
<CheckBox>Check grammar as you type</CheckBox>
<CheckBox>Hide grammatical errors in this document</CheckBox>
<CheckBox>Check grammar with spelling</CheckBox>
</StackPanel>
</GroupBox>
.9.7 .
, ..
318
9.
Expander
Expander ,
,
, Windows Forms! Expander GroupBox,
,
( ).
.9.8 Expander.
, .9.6,
GroupBox Expander:
<Expander Header="Grammar">
<StackPanel>
<CheckBox>Check grammar as you type</CheckBox>
<CheckBox>Hide grammatical errors in this document</CheckBox>
<CheckBox>Check grammar with spelling</CheckBox>
</StackPanel>
</Expander>
! WPF Button,
,
, .
, ,
, ,
(items controls).
10.
10
, WPF
,
,
- .
ItemsControl, , ContentControl,
Control.
ItemsControl Items ( ItemCollec
tion). ,
,
. , UIElement
, ( )
TextBlock, ,
ToString.
ListBox
.
ListBoxItem, :
<ListBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Button>Button</Button>
<Expander Header="Expander"/>
<sys:DateTime>1/1/2012</sys:DateTime>
<sys:DateTime>1/2/2012</sys:DateTime>
<sys:DateTime>1/3/2012</sys:DateTime>
</ListBox>
( sys:DateTime x:DateTime,
,
XAML-.)
320
10.
Items,
Items . ,
.10.1. UIElement (Button Expander)
. DateTime
, ToString.
.10.1. ListBox,
2 XAML , Items
. ,
, , Items
. ItemsControl
ItemsSource,
.
ItemsSource 13
.
,
.
:
(, -)
.
13.
Items ItemsSource, ItemsControl
, :
HasItems ,
XAML-.
C#
Items.Count.
IsGrouping , .
, , ,
.
321
ItemsCollection,
.
13.
AlternationCount AlternationIndex
-
. , AlternationCount 2,
,
. 14 ,
, .
DisplayMemberPath ;
( ),
.
ItemsPanel ,
,
.
.
DisplayMemberPath
. 10.2 , ,
ListBox DisplayMemberPath:
<ListBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
DisplayMemberPath="DayOfWeek">
<Button>Button</Button>
<Expander Header="Expander"/>
<sys:DateTime>1/1/2012</sys:DateTime>
<sys:DateTime>1/2/2012</sys:DateTime>
<sys:DateTime>1/3/2012</sys:DateTime>
</ListBox>
322
10.
ToString DayOfWeek
DayOfWeek.) Button Expander DayOfWeek,
TextBlock.
WPF
DisplayMemberPath
, WPF ,
. ,
,
.
,
, (..),
, C#.
.
, , , FirstButton
Button, Content
"OK". ("OK")
:
FirstButton.Content
(2):
FirstButton.Content.Length
('O'):
FirstButton.Content[0]
C#,
.
ItemsPanel
WPF,
,
, .
WPF ,
,
,
. -,
(items panel), ,
, .
,
5 (
, Panel). , ListBox
, XAML-
323
WrapPanel, Photo
Gallery 7 :
<ListBox>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
...
</ListBox>
XAML- ,
, C#:
FrameworkElementFactory panelFactory = new
FrameworkElementFactory(typeof(WrapPanel));
myListBox.ItemsPanel = new ItemsPanelTemplate(panelFactory);
FanCanvas,
21 :
<ListBox>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<custom:FanCanvas/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
...
</ListBox>
. 10.3
Photo Gallery ( ListBox Viewbox)
, .
, ListBox ,
.
324
10.
FAQ
ListBox ,
?
ListBox VirtualizingStackPanel,
.
, VirtualizingStackPanel, Orien
tation Horizontal:
<ListBox>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
...
</ListBox>
ItemsPanel Virtuali
zingStackPanel. WPF4 ,
, .
VirtualizingStackPanel.
VirtualizationMode Recycling.
() ,
, .
, ListBox, ItemsPre
senter, ItemsPanel:
<ControlTemplate TargetType="{x:Type ListBox}">
<Border ...>
<ScrollViewer Padding="{TemplateBinding Padding}" Focusable="false">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</ScrollViewer>
</Border>
<ControlTemplate.Triggers>
...
</ControlTemplate.Triggers>
</ControlTemplate>
ScrollViewer ,
. ,
,
ScrollViewer.
325
ListBox
:
ScrollViewer.HorizontalScrollBarVisibility Auto
ScrollViewer.VerticalScrollBarVisibility Auto
ScrollViewer.CanContentScroll true
ScrollViewer.IsDeferredScrollingEnabled false
CanContentScroll true, ,
false .
, .
IsDeferredScrollingEnabled false,
. true,
ScrollViewer
, .
, IsDeferredScrollingEnabled true
. , Microsoft Outlook
.
ListBox,
, ScrollViewer
:
<ListBox
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
ScrollViewer.CanContentScroll="False"
ScrollViewer.IsDeferredScrollingEnabled="True"
>
...
</ListBox>
ListBox , .
,
: , .
,
.
Selector, ItemsControl, ,
. ,
:
326
10.
SelectedIndex ,
, -1, .
.
SelectedItem .
SelectedValue .
, SelectedValue , SelectedItem.
SelectedValuePath
,
(SelectedValuePath DisplayMemberPath).
,
, .
Selector ,
:
IsSelected ,
( , ).
IsSelectionActive ,
, .
Selector SelectionChanged,
. 6
: , ,
ListBox,
.
WPF , Selector:
ComboBox
ListBox
ListView
TabControl
DataGrid
.
ComboBox
.10.4 ComboBox
. , .
, ,
.
, , Alt+
, Alt+ F4.
ComboBox DropDownOpened DropDownClosed
IsDropDownOpen.
. , ComboBox
DropDownOpened. ,
327
IsDropDownOpen ,
.
ComboBox ,
. -
,
. ,
Text ComboBox,
.
IsEditable IsReadOnly,
false. , StaysOpenOnEdit;
true, ,
( Microsoft Office
Win32).
,
. , ComboBox
( ,
). ,
ComboBox, .
10.1 XAML- ComboBox,
. Power
Point, Microsoft Office,
. Office
,
. .10.5
10.1, , ,
IsEditable true.
10.1. ComboBox ,
Microsoft Office
<ComboBox>
<!-- #1 -->
<StackPanel Orientation="Horizontal" Margin="5">
<Image Source="CurtainCall.bmp"/>
<StackPanel Width="200">
<TextBlock Margin="5,0" FontSize="14" FontWeight="Bold"
328
10.
VerticalAlignment="center">Curtain Call</TextBlock>
<TextBlock Margin="5" VerticalAlignment="center"
TextWrapping="Wrap">
Whimsical, with a red curtain background that represents
a stage.
</TextBlock>
</StackPanel>
</StackPanel>
<!-- #2 -->
<StackPanel Orientation="Horizontal" Margin="5">
<Image Source="Fireworks.bmp"/>
<StackPanel Width="200">
<TextBlock Margin="5,0" FontSize="14" FontWeight="Bold"
VerticalAlignment="center">Fireworks</TextBlock>
<TextBlock Margin="5" VerticalAlignment="center"
TextWrapping="Wrap">
Sleek, with a black sky containing fireworks. When you need
to celebrate PowerPoint-style, this design is for you!
</TextBlock>
</StackPanel>
</StackPanel>
... ...
</ComboBox>
IsEditable=False ( )
IsEditable=True
, "System.Windows.Controls.Stack
Panel" , TextSearch.
, ,
.
329
FAQ
IsEditable IsReadOnly
ComboBox?
IsEditable true, ComboBox .
IsReadOnly , ,
, IsReadOnly TextBox. , IsReadOnly
, IsEditable true, , IsEditable
true, , . .10.1
ComboBox
.
10.1. ComboBox
IsEditable IsReadOnly
IsEditable
IsReadOnly
false
false
,
( )
false
true
true
false
true
true
ComboBox TextSearch.TextPath
, ( )
. , DisplayMemberPath Selected
ValuePath;
.
10.1
TextBlock,
("Curtain Call" "Fireworks"). TextBlock
StackPanel,
StackPanel (
), TextBlock ( StackPanel).
, TextPath 10.1
:
<ComboBox IsEditable="True" TextSearch.TextPath="Children[1].Children[0].Text">
...
</ComboBox>
330
10.
, .
; , TextPath,
.
TextSearch Text;
, ComboBox.
Text ,
. 10.1
:
<ComboBox IsEditable="True">
<!-- #1 -->
<StackPanel TextSearch.Text="Curtain Call" Orientation="Horizontal" Margin="5">
...
</StackPanel>
<!-- #2 -->
<StackPanel TextSearch.Text="Fireworks" Orientation="Horizontal" Margin="5">
...
</StackPanel>
... ...
</ComboBox>
TextSearch.TextPath ComboBox
, TextSearch.Text . Text
Path , Text
, .
.10.6 TextSearch.
TextPath TextSearch.Text.
.10.6. TextSearch
, Office
331
TextSearch, IsTextSearch
Enabled ItemsControl false. IsTextSearchCaseSensitive,
ItemsControl ( false),
,
.
FAQ
SelectionChanged?
SelectionChanged ,
, ComboBox,
, .
SelectionChangedEventArgs
IList: AddedItems RemovedItems. AddedItems
, RemovedItems
. ,
:
void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
object newSelection = e.AddedItems[0];
}
, -
( )!
ComboBox ,
, IsEditable true, IsReadOnly false.
,
, SelectionChanged ,
AddedItems .
ComboBoxItem
ComboBox
ComboBoxItem. ( , ,
, .)
(, ComboBoxItem
). 10.1 :
<!-- #1 -->
<ComboBoxItem TextSearch.Text="Curtain Call">
<StackPanel Orientation="Horizontal" Margin="5">
...
</StackPanel>
332
10.
</ComboBoxItem>
<!-- #2 -->
<ComboBoxItem TextSearch.Text="Fireworks">
<StackPanel Orientation="Horizontal" Margin="5">
...
</StackPanel>
</ComboBoxItem>
... ...
, TextSearch.Text
ComboBoxItem, StackPanel
.
TextSearch.TextPath, Content.Children[1].Children[0].Text.
FAQ
ComboBoxItem?
ComboBoxItem IsSelected IsHighlighted
Selected Unselected. ComboBoxItem
( IsEditable false): ComboBox
,
, Content.
ComboBoxItem ( ),
, .
ComboBoxItem ,
ComboBox ( ,
TextBlock Label). :
<ComboBox>
<ComboBoxItem>Item 1</ComboBoxItem>
<ComboBoxItem>Item 2</ComboBoxItem>
</ComboBox>
ListBox
ListBox ComboBox,
, (
, ). . 10.7
ListBox, , 10.1.
, ListBox ,
. Selecti
onMode, (
SelectionMode):
Single , Com
boBox. .
333
SelectedItems,
.
Extended ,
.
,
Shift ( ) Ctrl
( , ).
ListBox Win32.
ComboBox ComboBoxItem, ListBox
ListBoxItem. .
ComboBoxItem ListBoxItem,
IsSelected Selected Unselected.
ListBox
ListBox SelectedItems,
SelectionMode,
Selector SelectedIndex, SelectedItem SelectedValue,
.
, SelectedItem
SelectedItems ( ,
), SelectedIndex SelectedValue
. , ,
, . ,
ListBox SelectedIndices SelectedValues.
334
10.
TextSearch,
ComboBox, ListBox. ,
.10.7 TextSearch.Text,
F , ListBox ,
Fireworks. TextSearch ,
S , S
System.Windows.Controls.StackPanel. (
!)
FAQ
ListBox?
ListBox .
,
. ,
, ,
false ScrollViewer.CanContentScroll,
ListBox, .
,
.
,
. , ,
, ,
CanContentScroll false
, .
FAQ
ListBox (
ItemsControl)?
, ItemsCollection,
,
ItemsControl. ItemsCollection SortDescriptions.
, System.Compo
nentModel.SortDescription. ,
,
. ,
ContentControl Content:
//
myItemsControl.Items.SortDescriptions.Clear();
// Content
myItemsControl.Items.SortDescriptions.Add(
new SortDescription("Content", ListSortDirection.Ascending));
335
FAQ
ItemsControl
, ,
UI Spy?
, FrameworkElement,
Name,
.
, ,
AutomationProperties.
AutomationID ( System.Windows.Automation).
ListView
ListView, ListBox, ,
ListBox, , Extended
SelectionMode. ListView View,
,
ItemsPanel.
View ViewBase, .
WPF , GridView.
(Details) Windows. (
- WPF GridView DetailsView.)
.10.8 ListView,
XAML-, , sys
System mscorlib.dll:
<ListView>
<ListView.View>
<GridView>
<GridViewColumn Header="Date"/>
<GridViewColumn Header="Day of Week"
DisplayMemberBinding="{Binding DayOfWeek}"/>
<GridViewColumn Header="Year" DisplayMemberBinding="{Binding Year}"/>
</GridView>
</ListView.View>
<sys:DateTime>1/1/2012</sys:DateTime>
<sys:DateTime>1/2/2012</sys:DateTime>
<sys:DateTime>1/3/2012</sys:DateTime>
</ListView>
GridView Columns,
GridViewColumn, ,
. WPF ListViewItem,
ListBoxItem. DateTime
ListViewItem, .
336
10.
, ListView,
, ListBox,
DisplayMemberBinding GridView
Column. , ListView
, .
, DisplayMemberPath, ItemsCont
rol, DisplayMemberBinding
(. 13).
, GridView -
Windows, :
.
.
.
GridView
, , , .
( SortDescriptions),
,
, . , ListView
GridView DataGrid. ,
WPF4 DataGrid, GridView
.
TabControl
, TabControl,
. . 10.9 , TabControl
. ,
TabStripPlacment ( Dock) (Left),
(Right) (Bottom).
TabControl . -
.
:
337
<TabControl>
<TextBlock>Content for Tab 1.</TextBlock>
<TextBlock>Content for Tab 2.</TextBlock>
<TextBlock>Content for Tab 3.</TextBlock>
</TabControl>
TabItem , Header
GroupBox Expander.
, TabItem
.
, null SelectedItem -1
SelectedIndex.
DataGrid
DataGrid
, ,
.
(, System.Data.DataTable ADO.NET).
Visual Studio , LINQ to SQL,
.
10.2 XAML- DataGrid,
Record:
public class Record
{
338
public
public
public
public
public
}
10.
string FirstName {
string LastName {
Uri Website {
bool IsBillionaire {
Gender Gender {
get;
get;
get;
get;
get;
set;
set;
set;
set;
set;
}
}
}
}
}
Gender :
public enum Gender
{
Male,
Female
}
, .10.10 (
Record), Columns.
10.2. DataGrid
<DataGrid IsReadOnly="True"
xmlns:local="clr-namespace:Listing10_2"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<!--
DataGridComboBoxColumn: -->
<DataGrid.Resources>
<ObjectDataProvider x:Key="genderEnum" MethodName="GetValues"
ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="local:Gender"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</DataGrid.Resources>
<!-- : -->
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>
<DataGridHyperlinkColumn Header="Website" Binding="{Binding Website}"/>
<DataGridCheckBoxColumn Header="Billionaire?"
Binding="{Binding IsBillionaire}"/>
<DataGridComboBoxColumn Header="Gender" SelectedItemBinding="{Binding Gender}"
ItemsSource="{Binding Source={StaticResource genderEnum}}"/>
</DataGrid.Columns>
<!-- : -->
<local:Record FirstName="Adam" LastName="Nathan"
Website="http://adamnathan.net" Gender="Male"/>
<local:Record FirstName="Bill" LastName="Gates"
Website="http://twitter.com/billgates" IsBillionaire="True" Gender="Male"/>
</DataGrid>
339
DataGrid
, ,
false : CanUserReor
derColumns, CanUserResizeColumns, CanUserResizeRows CanUserSortColumns.
GridLinesVisibility HeadersVisibility
.
10.2 ,
DataGrid:
DataGridTextColumn ,
TextBlock,
TextBox.
DataGridHyperlinkColumn
, . , ,
(,
). .
DataGridCheckBoxColumn ,
CheckBox,
true, false.
DataGridComboBoxColumn ,
TextBlock,
ComboBox, .
WPF :
DataGridTemplateColumn
.
CellTemplate CellEditingTemplate.
, DataGrid,
ItemsSource,
.
DataGridTextColumn, URI Data
GridHyperlinkColumn, Da
taGridCheckBoxColumn, Data
GridComboBoxColumn (
).
340
10.
, DataGrid:
<DataGrid Name="dataGrid" />
, .10.10,
ItemsSource, :
dataGrid.ItemsSource = new Record[]
{
new Record { FirstName="Adam", LastName="Nathan", Website=
new Uri("http://adamnathan.net"), Gender=Gender.Male },
new Record { FirstName="Bill", LastName="Gates", Website=
new Uri("http://twitter.com/billgates"), Gender=Gender.Male,
IsBillionaire=true }
};
,
. .10.11.
,
DataGrid .10.11
.
Items DataGrid .
,
TextBox, CheckBox ,
Gender ()
ComboBox . ,
, ,
F2.
ItemsSource. (, IsBillionaire (
)
. , - .)
DataGrid - ,
.
,
AutoGeneratingColumn, .
AutoGeneratedColumns.
341
,
AutoGenerateColumns false.
DataGrid
SelectionMode SelectionUnit. SelectionMode
Single ,
Extended (
).
SelectionUnit:
Cell .
FullRow .
CellOrRowHeader (
).
Shift
, Ctrl
.
Selected, SelectedItems
. DataGrid
10.2 Record.
SelectedCellChanged, SelectedCells
DataGridCellInfo,
. DataGridRow
DataGridCell Selected, IsSelec
ted true.
,
.
CurrentCell. , CurrentColumn
, CurrentCell,
CurrentItem , ,
CurrentCell.
MultiSelector,
Selector WPF 3.5.
WPF , Da
taGrid MultiSelector.
DataGrid ,
, ,
.
. ,
DataGrid (, Ctrl+C
342
10.
), ClipboardCopyMode.
:
ExcludeHeader .
.
IncludeHeader .
None .
. DataGrid (
UIElement , ,
), .
EnableRowVirtualization ( false,
) EnableColumnVirtualization ( true,
). EnableColumnVirtualization
true,
.
. DataGrid
RowDe
tailsTemplate. :
<DataGrid ...>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<TextBlock Margin="10" FontWeight="Bold">Details go here.</TextBlock>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
...
</DataGrid>
RowDetailsTemplate
, ,
TextBlock. .10.12 ,
.
.10.12.
DataGrid
( ),
RowDetailsVisibilityMode, :
343
VisibleWhenSelected
. .
Visible .
Collapsed .
. DataGrid
. ,
.
Microsoft Excel. :
.
,
FrozenColumnCount , 0. .10.13 ,
DataGrid 10.2, FrozenColumnCount 2.
, , , -
.
FAQ
DataGrid ?
, .
. AreRowDetails
Frozen true,
.p
,
, ItemsSource
.
ItemsSource ,
DataGrid .
344
10.
List<Record> (
):
dataGrid.ItemsSource = new List<Record>(
new Record[]
{
new Record { FirstName="Adam", LastName="Nathan", Website=
new Uri("http://adamnathan.net"), Gender=Gender.Male },
new Record { FirstName="Bill", LastName="Gates", Website=
new Uri("http://twitter.com/billgates"), Gender=Gender.Male,
IsBillionaire=true }
}
);
DataGrid ,
. DataGrid
, (
F2), ( Esc),
( Enter) ( Delete).
IsReadOnly
true, ,
false CanUserAddRows CanUserDeleteRows
. 10.2 IsReadOnly true,
,
Record .
( ) ,
,
: PreparingCellForEdit, BeginningEdit, CellEditEnding/RowEditEnding Initiali
zeNewItem.
CanUserAddRows CanUserDeleteRows
false!
, CanUserAddRows CanUser
DeleteRows false,
true! , IsReadOnly IsEnabled DataGrid
false, false .
:
( CanAddNew CanRemove,
IEditableCollectionView), CanUserAddRows, CanUserDeleteRows
false. , ,
IEditableCollectionView . 13.
345
Menu
Menu
( ). Items
Control Menu IsMainMenu. true
( ), Menu
Alt F10, ,
Win32.
Menu ,
, ,
MenuItem Separator. .10.14
, 10.3.
10.3. MenuItem Separator
<Menu>
<MenuItem Header="_File">
<MenuItem Header="_New..."/>
<MenuItem Header="_Open..."/>
<Separator/>
<MenuItem Header="Sen_d To">
<MenuItem Header="Mail Recipient"/>
<MenuItem Header="My Documents"/>
</MenuItem>
</MenuItem>
<MenuItem Header="_Edit">
...
</MenuItem>
<MenuItem Header="_View">
...
</MenuItem>
</Menu>
MenuItem
( HeaderedItemsControl)
. MenuItem Header
( , , . .10.14).
Items, , ,
. Button Label, MenuItem
, .
346
10.
.10.14. WPF
Separator , , Menu
Item, , .10.14.
:
ToolBar StatusBar.
Menu , MenuItem
. .
Icon ,
Header. Icon , Header,
.
IsCheckable MenuItem CheckBox.
InputGestureText
( - ,
Ctrl+O).
MenuItem : Checked, Unchecked, Submenu
Opened, SubmenuClosed Click.
Click,
Command MenuItem.
InputGestureText MenuItem
!
WPF , Windows Forms Visual Ba
sic6, InputGestureText MenuItem "Ctrl+O"
, Ctrl+O
! .
MenuItem ,
Command.
, InputGestureText MenuItem
,
- .
347
Command MenuItem
RoutedUICommand, Header
Text . ,
Header .
FAQ
Menu , ?
Menu ,
ListBox
ItemsPanel,
StackPanel:
<Menu>
<Menu.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</Menu.ItemsPanel>
...
</Menu>
StackPanel ,
Orientation . .10.15.
.10.15.
, 90 (
Microsoft Office ,
),
RotateTransform.
ContextMenu
ContextMenu , Menu; ,
MenuItem Separator.
ContextMenu .
, ContextMenu FrameworkElement
348
10.
FrameworkContentElement. ,
(
Shift+F10).
.10.16 ,
ListBox (, ,
10.3):
<ListBox>
<ListBox.ContextMenu>
<ContextMenu>
... MenuItems 10.3...
</ContextMenu>
</ListBox.ContextMenu>
...
</ListBox>
.10.16. WPF
FAQ
,
?
ToolTipService, ContextMenuService
ShowOnDisabled . :
<ListBox ContextMenuService.ShowOnDisabled="True">
<ListBox.ContextMenu>
...
</ListBox.ContextMenu>
...
</ListBox>
349
, ToolTip ToolTipService,
,
. ContextMenu
ContextMenuService, .
, ,
ContextMenu.
TreeView, ToolBar StatusBar
, ,
.
TreeView
TreeView ,
, .10.17. Aero
, , Luna,
.
Aero
Luna
TreeView, Menu, .
. TreeView
, -, TreeViewItem.
TreeViewItem, MenuItem, .
Header , Items
(, TreeViewItem).
TreeView, .10.17, XAML:
<TreeView>
<TreeViewItem Header="Desktop">
<TreeViewItem Header="Computer">
...
350
10.
</TreeViewItem>
<TreeViewItem Header="Recycle Bin">
...
</TreeViewItem>
<TreeViewItem Header="Control Panel">
<TreeViewItem Header="Programs"/>
<TreeViewItem Header="Security"/>
<TreeViewItem Header="User Accounts"/>
</TreeViewItem>
<TreeViewItem Header="Network">
...
</TreeViewItem>
</TreeViewItem>
</TreeView>
TreeView Selector
API TreeView Selector,
,
. Tree
View SelectedItem SelectedValue ( Selec
tedIndex). SelectedItemChanged,
, OldValue NewValue,
TreeView .
, WPF4. ,
- , Rad
TreeView Telerik (http://telerik.com/products/wpf/treeview.aspx).
TreeView
, ListBox, .
WPF 4 TreeView ,
Virtuali
zingStackPanel.IsVirtualizing TreeView true.
,
.
351
TreeView TreeViewItem!
TextBlock, ,
, -
, TextBlock, .
Foreground , TextBlock
,
. (
TreeViewItem,
.) ,
. TreeViewItem (
) TextBlock,
.
ToolBar
ToolBar ( )
( )
. .10.18
, XAML-:
<ToolBar RenderOptions.BitmapScalingMode="NearestNeighbor">
<Button><Image Source="copy.gif"/></Button>
<Separator/>
<ToggleButton><Image Source="bold.gif"/></ToggleButton>
<ToggleButton><Image Source="italic.gif"/></ToggleButton>
<ToggleButton><Image Source="underline.gif"/></ToggleButton>
<Separator/>
<ToggleButton><Image Source="left.gif"/></ToggleButton>
<ToggleButton><Image Source="right.gif"/></ToggleButton>
<ToggleButton><Image Source="justify.gif"/></ToggleButton>
<Separator/>
<Label>Zoom</Label>
<ComboBox>
...
</ComboBox>
<Separator/>
<Button><Image Source="superscript.gif"/></Button>
<Button><Image Source="subscript.gif"/></Button>
...
</ToolBar>
352
10.
, Button ComboBox
, . , Separator
, , Menu. ToolBar
, .
ToolBar ,
ToolBarTray, Frame
workElement. ToolBarTray ToolBar (
ToolBars) , IsLocked true,
.
( ToolBarTray IsLocked,
ToolBar.) ToolBarTray
Orientation; Vertical,
ToolBar .
ToolBar ,
, .
,
, .10.19.
,
OverflowMode ToolBar. ,
(AsNeeded ), (Always) (Never).
.10.19. ,
, Visual Studio,
ToolBar.OverflowMode Never ,
Menu "_Add or Remove Buttons" (
), ToolBar.OverflowMode
Always ( ).
MenuItem ,
, .
353
,
RenderOptions.BitmapScalingMode, NearestNeighbor.
,
. ToolBar
.
ToolBar,
Button . ,
. ( Popup Tool
Bar.) - .10.19
, .
ToolBar
:
<ToolBar>
<Button>A</Button>
<Menu>
<MenuItem Header="B"/>
<MenuItem Header="C"/>
</Menu>
<Button>D</Button>
</ToolBar>
ToolBar, Tab,
A B, C, D A
. ,
B C.
KeyboardNavigation System.Windows.Input
. ,
Tab , Key
boardNavigation.TabNavigation ToolBar Continue ( Cyc
le).
, Menu KeyboardNavigation.DirectionalNa
vigation, Continue.
354
10.
Header ToolBar
ToolBar (
MenuItem TreeViewItem). Header ,
ToolBarTray.
, ,
ToolBar ( Header),
.
, .
StatusBar
StatusBar , Menu,
, .10.20.
Window .
StatusBar, .10.20,
XAML-:
<StatusBar RenderOptions.BitmapScalingMode="NearestNeighbor">
<Label>27 Items</Label>
<Separator/>
<Label>Zoom</Label>
<ComboBox>
...
</ComboBox>
<Separator/>
<Button><Image Source="justify.gif"/></Button>
</StatusBar>
StatusBar Separa
tor , ,
ToolBar. StatusBar ( Separator)
StatusBarItem, .
, 5.
355
FAQ
,
?
,
. , 25% StatusBar,
75%. ,
ItemsPanel Grid :
<StatusBar>
<StatusBar.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
</StatusBar.ItemsPanel>
<StatusBarItem Grid.Column="0">...</StatusBarItem>
<Separator Grid.Column="1"/>
<StatusBarItem Grid.Column="2">...</StatusBarItem>
</StatusBar>
, StatusBar
Grid.Column ( , ItemsPanel
Grid), 0. ,
, Sta
tusBarItem Separator. , (Label, ComboBox Button
StatusBar) StatusBarItem,
. ,
, StatusBarItem .
, ,
WPF. WPF-
, ,
. , ,
!
. ,
WPF.
, .
Image
Text Ink
11.
11
,
, . , Image, , ProgressBar Slider, , ,
WPF ,
. Calendar DatePicker WPF4.
, FrameworkContent
Element ( Control),
. , WPF.
Image
System.Windows.Controls.Image
( BMP, PNG, GIF, JPG .).
Source System.Windows.Media.ImageSource,
System.Windows.Media.ImageSourceConverter XAML
, :
<Image Source="zoom.gif"/>
ImageSource , URL, . (
, ,
.) Image Stretch
StretchDirection, 5
, .
Image ,
, .
Image RenderOptions.BitmapScalingMode,
357
Image
.
NearestNeighbor
, .
ToolBar Sta
tusBar, Photo Gallery 7
. :
<Image RenderOptions.BitmapScalingMode="NearestNeighbor" Source="zoom.gif"/>
,
. .11.1
Photo Gallery NearestNeighbor .
RenderOptions.BitmapScalingMode="NearestNeighbor"
ImageSource, Source
Image ImageSource,
. , BitmapImage ,
DecodePixelWidth DecodePixelHeight,
, ,
. FormatConvertedBitmap
Image, ,
. XAML-
FormatConvertedBitmap ,
.11.2:
<StackPanel Orientation="Horizontal">
<!-- , Pbgra32: -->
<Image Source="photo.jpg" />
<!-- : -->
<Image>
<Image.Source>
<FormatConvertedBitmap Source="photo.jpg" DestinationFormat="Gray32Float" />
</Image.Source>
</Image>
<!-- - : -->
<Image>
358
11. ,
<Image.Source>
<FormatConvertedBitmap Source="photo.jpg" DestinationFormat="BlackWhite" />
</Image.Source>
</Image>
</StackPanel>
System.Win
dows.Media.PixelFormats.
Pbgra32
( )
Gray32Float
BlackWhite
.11.2. Image
(. )
Text Ink
TextBlock Label WPF
, .
TextBlock,
:
TextBox
RichTextBox
PasswordBox
InkCanvas
WPF4,
.
WPF . ( ,
WPF
!) WPF
/
.
Text Ink
359
, ,
.
, ,
WPF .
, WPF4 .
, , -
. (, WPF
,
,
.)
.
, , TextOptions.Text
FormattingMode. ,
, Win
dow;
-. TextFormattingMode
Display, WPF 4,
, GDI.
,
(
).
TextFormattingMode ,
,
Ideal.
,
, .
,
, (
).
TextOptions.TextRenderingMode
ClearType, Grayscale, Aliased Auto
(antialiasing). Auto ( )
ClearType,
, Grayscale.
. 11.3 TextFormattingMode
TextRenderingMode, Auto,
.
.11.3. FontSize=11
360
11. ,
TextOptions.TextHintingMode Fixed,
Animated Auto ,
.
FAQ
Display
TextFormattingMode, ?
. (FontSize 15
), Ideal ,
Display, . ,
Display ,
.
Display
ScaleTransform, WPF
, . (
,
, ,
.) ,
, Display .
TextBlock
TextBlock ,
, FontFamily, FontSize, FontStyle, FontWeight FontStretch.
TextBlock ,
Text, Inlines.
, Text,
:
<!-- TextBlock.Inlines: -->
<TextBlock>Text in a TextBlock</TextBlock>
, ,
, Run.
XAML- :
<TextBlock><Run Text="Text in a TextBlock"/></TextBlock>
, , ( Text
Run):
<TextBlock><Run>Text in a TextBlock</Run></TextBlock>
Run .
Run , ,
TextBlock Run,
. , TextBlock
:
Text Ink
361
<TextBlock>
<Run>Text</Run>
<Run> in</Run>
<Run> a</Run>
<Run> TextBlock</Run>
</TextBlock>
. Run
,
, TextBlock,
: FontFamily, FontSize, FontStretch, FontStyle, FontWeight, Foreground TextDeco
rations. XAML-,
.11.4:
<TextBlock>
<Run FontStyle="Italic" FontFamily="Georgia" Foreground="Red">Rich</Run>
<Run FontSize="30" FontFamily="Comic Sans MS" Foreground="Blue"> Text </Run>
<Run FontFamily="Arial Black" Foreground="Orange" FontSize="100">in</Run>
<Run FontFamily="Courier New" FontWeight="Bold" Foreground="Green"> a </Run>
<Run FontFamily="Verdana" TextDecorations="Underline">TextBlock</Run>
</TextBlock>
.11.4. Run
TextBlock
, , , ,
, .
,
TextBlock. , TextBlock
,
. Run Inline;
.
TextBlock
TextBlock Text,
. Inlines
XAML, .
, ( HTML).
362
11. ,
Inlines TextBlock
Text.
- Text,
Inlines. , TextBlock .11.4
Text "Rich Text in a TextBlock", .
Run
TextBlock:
<TextBlock>Text in a TextBlock</TextBlock>
:
<TextBlock><Run>Text in a TextBlock</Run></TextBlock>
. ,
LineBreak ( Inline) :
<TextBlock>Text in<LineBreak/>a TextBlock</TextBlock>
:
<TextBlock><Run>Text in<LineBreak/>a TextBlock</Run></TextBlock>
, Run
(Text) , LineBreak
. Text
Block (Inlines) Run,
LineBreak. XAML-:
<TextBlock>Text in<LineBreak/>a TextBlock</TextBlock>
TextBlock, Run,
LineBreak:
<TextBlock><Run>Text in</Run><LineBreak/><Run>a TextBlock</Run></TextBlock>
TextBox
TextBox, .11.5,
.
WPF, TextBox
System.Object, Text.
Text Ink
363
TextBox ,
, Cut, Copy, Paste, Undo
Redo (. 6 : , ,
) !
TextBox
( , ..),
. TextChanged SelectionChanged.
TextBox (
), .
TextBox , ,
TextWrapping Wrap WrapWithOverflow. Wrap
,
, .
WrapWithOverflow , ,
. ( TextBlock
TextWrapping.)
FAQ
, TextBox
?
AcceptsReturn true,
Enter . , TextBox
.
Text , NewLine,
AcceptsReturn. ,
.
,
TextBox.
TextBox ( RichTextBox),
SpellCheck.IsEnabled true.
, Microsoft Word:
,
, . WPF
, Microsoft Office
( ).
WPF .
364
11. ,
RichTextBox
RichTextBox , TextBox,
(
). .11.6 RichTextBox
.
PasswordBox
PasswordBox TextBox,
. ,
.11.7.
PasswordBox TextBoxBase,
, Cut, Copy, Undo Redo (
Paste), .
, !
,
PasswordChar. ( ,
, .)
PasswordBox Password.
System.Security.SecureString. SecureString
, System.String
Text Ink
365
,
.
TextboxPasswordChanged.
RoutedEventHandler,
.
, Password.
InkCanvas
InkCanvas
( ,
). .11.8. ,
InkCanvas ,
FrameworkElement, ,
( , ).
InkCanvas
. ,
.
System.Windows.Ink.Stroke,
Strokes. InkCanvas
UIElement Children ( ).
,
.11.9.
.11.9.
366
11. ,
,
Window:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
SizeToContent="WidthAndHeight">
<Grid>
<InkCanvas>
<Image Source="http://adamnathan.net/blog/images/anathan.png"/>
</InkCanvas>
</Grid>
</Window>
SizeToContent
, Window
, !
DefaultDrawingAttributes
(, ..). Stroke Drawing
Attributes,
.
InkCanvas ,
( )
EditingMode Editing
ModeInverted. ActiveEditingMode
, .
InkCanvasEditingMode,
:
Ink .
EditingMode.
InkAndGesture Ink, .
(Up, Down, Circle, ScratchOut, Tap .)
System.Windows.Ink.ApplicationGesture.
GestureOnly , .
EraseByStroke , .
EditingModeInverted.
EraseByPoint ,
( ).
Select UIElement ,
, InkCanvas.
None .
Select ,
, ,
. InkCanvas 15 ,
, ,
367
, ,
.
,
!
. WPF
,
.
TextBlock Label
, TextBox RichTextBox
. WPF
!
WPF , ,
, .
.
( FlowDocument)
, ,
. ,
.
FlowDocument FrameworkContentElement, Frame
workElement, .
FrameworkContentElement, FrameworkElement,
, WPF,
. FrameworkCon
tentElement - FrameworkElement.
FAQ
WPF
XML Paper Specification (XPS)?
,
, XPS-
, . .NET Framework
XPS- (
System.Windows.Xps System.Windows.Documents),
, Microsoft Word.
WPF- XPS-
FixedDocument DocumentViewer.
368
11. ,
, FrameworkContentElement, Text
Element , ,
FlowDocument.
TextElement ( System.Windows.
Documents) ,
.
XAML- FlowDocument,
Paragraph ( TextElement)
.
<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Paragraph FontSize="22" FontWeight="Bold">Chapter 1</Paragraph>
<Paragraph FontSize="35" FontWeight="Bold">Why WPF?</Paragraph>
<Paragraph>
In movies and on TV, the ...
</Paragraph>
<Paragraph>...</Paragraph>
<Paragraph>...</Paragraph>
...
</FlowDocument>
.11.10 XAML-.
FlowDocument XAML-,
.
TextElement Block Inline (
, TextElement). Block
,
, Inline , , ,
(
). FlowDocument Block
. ( Blocks
BlocksCollection.) Inline
, .
369
.11.10. FlowDocument
Block
WPF :
Paragraph Inlines,
. XAML Paragraph
,
Run, Inline, Inlines
, TextBlock.
Section ,
. ,
, Background
Foreground.
List ListItem
, . ListItem
Block, List
Paragraph ListItem.
MarkerStyle ( TextMarkerStyle)
Box, Circle, Disc ( )
Square Decimal, LowerLatin, UpperLatin, LowerRoman UpperRo
man. , MarkerSty
le None.
Table ,
Grid, HTML-. Table,
Grid, Block (,
).
BlockUIContainer UIElement. Block
UIContainer WPF-
FlowDocument: Image, , MediaEle
ment, Button, Viewport3D ..
370
11. ,
11.1
FlowDocument.
.11.11.
11.1. FlowDocument, .11.11
<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Section LineHeight="2" Foreground="White" Background="Black">
<Paragraph FontSize="18">WPF 4 Unleashed</Paragraph>
<Paragraph FontSize="30" FontWeight="Bold">Notes from Chapter 1</Paragraph>
</Section>
<Paragraph>Here are some highlights of WPF:</Paragraph>
<List>
<ListItem>
<Paragraph>Broad integration</Paragraph>
</ListItem>
<ListItem>
<Paragraph>Resolution independence</Paragraph>
</ListItem>
<ListItem>
<Paragraph>Hardware acceleration</Paragraph>
</ListItem>
<ListItem>
<Paragraph>Declarative programming</Paragraph>
</ListItem>
<ListItem>
<Paragraph>Rich composition and customization</Paragraph>
</ListItem>
</List>
<BlockUIContainer>
<Viewbox>
<StackPanel Orientation="Horizontal">
<Image Source="diagram.jpg" Margin="5"/>
<TextBlock VerticalAlignment="Center" Width="100" TextWrapping="Wrap">
The technologies in the .NET Framework.
</TextBlock>
</StackPanel>
</Viewbox>
</BlockUIContainer>
<Paragraph>
Here's another version of the diagram, as a Table:
</Paragraph>
<Table CellSpacing="5" Padding="15" FontFamily="Segoe UI">
<Table.Background>
<LinearGradientBrush>
<GradientStop Color="Yellow" Offset="0"/>
<GradientStop Color="Orange" Offset="1"/>
</LinearGradientBrush>
</Table.Background>
<!-- : -->
<Table.Columns>
<TableColumn/>
<TableColumn/>
<TableColumn/>
<TableColumn/>
</Table.Columns>
<!-- : -->
<TableRowGroup>
<TableRow>
<TableCell ColumnSpan="4" TextAlignment="Center">
<Paragraph FontWeight="Bold">.NET Framework</Paragraph>
</TableCell>
</TableRow>
<TableRow>
<TableCell BorderBrush="Black" BorderThickness="2"
Background="LightGray" TextAlignment="Center" LineHeight="70">
<Paragraph FontWeight="Bold">WPF</Paragraph>
</TableCell>
<TableCell BorderBrush="Black" BorderThickness="2"
Background="LightGray" TextAlignment="Center">
<Paragraph FontWeight="Bold">WCF</Paragraph>
</TableCell>
<TableCell BorderBrush="Black" BorderThickness="2"
Background="LightGray" TextAlignment="Center">
<Paragraph FontWeight="Bold">WF</Paragraph>
</TableCell>
<TableCell BorderBrush="Black" BorderThickness="2"
Background="LightGray" TextAlignment="Center">
<Paragraph FontWeight="Bold">WCS</Paragraph>
</TableCell>
</TableRow>
<TableRow>
<TableCell BorderBrush="Black" BorderThickness="2"
Background="LightGray" TextAlignment="Center">
<Paragraph FontWeight="Bold">ADO.NET</Paragraph>
</TableCell>
<TableCell BorderBrush="Black" BorderThickness="2"
Background="LightGray" TextAlignment="Center">
<Paragraph FontWeight="Bold">ASP.NET</Paragraph>
</TableCell>
<TableCell BorderBrush="Black" BorderThickness="2"
Background="LightGray" TextAlignment="Center">
<Paragraph FontWeight="Bold">Windows Forms</Paragraph>
</TableCell>
<TableCell BorderBrush="Black" BorderThickness="2"
Background="LightGray" TextAlignment="Center">
<Paragraph FontWeight="Bold">...</Paragraph>
</TableCell>
371
372
11. ,
</TableRow>
</TableRowGroup>
</Table>
</FlowDocument>
Paragraph
Section
Table
List
BlockUIContainer
.11.11. FlowDocument,
Paragraph ,
Section , Paragraph
Foreground, Background LineHeight. List
, .
BlockUIContainer Image,
TextBlock.
StackPanel Viewbox,
.
,
Table. , API Table (,
Table XAML-) Grid.
TableColumn Columns
( ColumnDefinitions Grid),
. , Table
TableRowGroup, TableRow
, , .
TableCell TableRow
, ColumnSpan
. TableCell , Block,
, Paragraph.
373
Table TableRowGroup! ,
, .
. 11.11 ,
Image. ,
. Table ,
.
, . ,
,
. .11.12 , .
.11.12. .11.11
2, 3
Inline
Inline Paragraph,
. ,
Paragraph ,
Inline. , Paragraph, XAML,
, Run,
Inline. Run Text,
.
, Paragraph, XAML
:
<Paragraph>Here are some highlights of WPF:</Paragraph>
C#:
Paragraph p = new Paragraph(new Run("Here are some highlights of WPF:"));
Inline
: (span), .
374
11. ,
. Bold,
Italic, Underline Hyperlink 7.
Span, Paragraph
. Paragraph
(
, ..) , FontWeight
FontStyle,
, .
Paragraph, .11.13,
:
<Paragraph>
<Bold>bold</Bold>
<Italic>italic</Italic>
<Underline>underline</Underline>
<Hyperlink>hyperlink</Hyperlink>
<Span BaselineAlignment="Superscript">superscript</Span>
<Span BaselineAlignment="Subscript">subscript</Span>
<Span>
<Span.TextDecorations>
<TextDecoration Location="Strikethrough"/>
</Span.TextDecorations>
strikethrough
</Span>
</Paragraph>
.11.13.
TextBlock Inline,
Paragraph
TextBlock, -. , Label
.
375
, Paragraph
Run. , ,
Paragraph,
.11.14:
<Paragraph>
a<Bold>b<Italic>c<Underline>d<Hyperlink>e</Hyperlink>f</Underline>g</Italic>h
</Bold>i
</Paragraph>
. WPF Inline, ,
Block. Figure
Floater AnchoredBlock.
Figure - -FlowDocument,
FlowDocument.
, Figure. , FlowDocument
1 , (
).
:
<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Paragraph FontSize="22" FontWeight="Bold">Chapter 1</Paragraph>
<Paragraph FontSize="35" FontWeight="Bold">Why WPF?</Paragraph>
<Paragraph>
<Figure Width="130">
<BlockUIContainer>
<Image Source="wpf.png"/>
</BlockUIContainer>
</Figure>
In movies and on TV, the ...
</Paragraph>
<Paragraph>...</Paragraph>
<Paragraph>...</Paragraph>
...
</FlowDocument>
Figure Block, ,
Table, Paragraph .
BlockUIContainer,
. .11.15.
Figure HorizontalAnchor
VerticalAnchor ( FigureHorizontalAnchor FigureVerticalAnchor
376
11. ,
.11.15. FlowDocument
Figure, Image
Floater Figure.
Block,
, .
HorizontalAnchor VerticalAnchor
HorizontalAlignment ( HorizontalAlignment),
Left, Center, Right Stretch.
Figure,
Floater.
Inline. Inline
,
Span AnchoredBlock. LineBreak,
. LineBreak
, .
FlowDocument , ,
BreakPageBefore Paragraph,
. BreakPageBefore Block,
Section, List, BlockUIContainer Table.
377
HorizontalAnchor="ColumnLeft"
HorizontalAnchor="PageCenter"
HorizontalAnchor="PageRight" VerticalAnchor="PageTop"
.11.16. Figure
HorizontalAnchor VerticalAnchor
378
11. ,
, Inline, InlineUIContainer,
BlockUIContainer , Para
graph . Block
UIContainer, MediaElement, Button,
Viewport3D ..,
, .
, .11.17, ,
RSS- Hyperlink :
<Paragraph>
You can read more about this on my blog (
<Hyperlink NavigateUri="http://blogs.msdn.com/adam_nathan/rss.xml">
subscribe
</Hyperlink>
<InlineUIContainer>
<Image Width="14" Source="rss.gif"/>
</InlineUIContainer>
), which I try to update once a month.
</Paragraph>
, FlowDocument (
) RichTextBox. ,
RichTextBox IsReadOnly true, RichTextBox
.
WPF
. , ,
, :
FlowDocumentScrollViewer
, - Microsoft Word
( RichTextBox,
ScrollViewer).
FlowDocumentPageViewer
, Microsoft Word.
FlowDocumentReader FlowDocumentScrollViewer Flow
DocumentPa
geViewer
, . (
, FlowDocument
XAML-.)
379
FlowDocumentScrollViewer
FlowDocumentPageViewer
FlowDocumentReader
.11.18. 1 FlowDocument
.11.18
FlowDocument, .
380
11. ,
FlowDocumentReader (
XPS- PDF-),
, , ,
. FlowDocumentPageViewer, FlowDocumentReader (
)
,
.
, FlowDocumentScrollViewer
, , ,
IsToolBarVisible true.
FlowDocument ( Docu
mentViewer, FixedDocument)
,
. ,
.
,
. AnnotationService
System.Windows.Annotations,
:
CreateTextStickyNoteCommand Sticky
NoteControl .
CreateInkStickyNoteCommand Sti
ckyNoteControl .
DeleteStickyNotesCommand
StickyNoteControl.
CreateHighlightCommand ,
.
ClearHighlightsCommand
.
11.2 Window, FlowDocu
mentReader .
.
11.2. Window1.xaml FlowDocument
Reader
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:a="clr-namespace:System.Windows.Annotations;assembly=PresentationFramework"
381
Title="FlowDocumentReader + Annotations"
x:Class="Window1" Initialized="OnInitialized" Closed="OnClosed">
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label>Control Annotations:</Label>
<Button Command="a:AnnotationService.CreateTextStickyNoteCommand"
CommandTarget="{Binding ElementName=reader}">
Create Text Note
</Button>
<Button Command="a:AnnotationService.CreateInkStickyNoteCommand"
CommandTarget="{Binding ElementName=reader}">
Create Ink Note
</Button>
<Button Command="a:AnnotationService.DeleteStickyNotesCommand"
CommandTarget="{Binding ElementName=reader}">
Remove Note
</Button>
<Button Command="a:AnnotationService.CreateHighlightCommand"
CommandParameter="{x:Static Brushes.Yellow}"
CommandTarget="{Binding ElementName=reader}">
Create Yellow Highlight
</Button>
<Button Command="a:AnnotationService.ClearHighlightsCommand"
CommandTarget="{Binding ElementName=reader}">
Remove Highlight
</Button>
</StackPanel>
<FlowDocumentReader x:Name="reader">
<FlowDocument>
...
</FlowDocument>
</FlowDocumentReader>
</StackPanel>
</Window>
.NET System.Windows.Annotations
XML a,
AnnotationService. AnnotationService PresentationFramework,
- WPF
XML. ,
FlowDocumentReader.
,
.
OnInitialized OnClosed,
XAML-. 11.3
, 11.2.
382
11. ,
System;
System.IO;
System.Windows;
System.Windows.Annotations;
System.Windows.Annotations.Storage;
OnInitialized OnClosed
AnnotationService, FlowDocumentReader.
Stream,
. 11.3
XML- .
(
, storage.xml ).
383
. 11.19 ,
.
.11.19.
FlowDocument
StickyNoteControl, ,
WPF ( System.Win
dows.Controls). ,
.
, .
,
.
RangeBase. double,
: Value, Minimum,
Maximum. ValueChanged.
: Progress
Bar Slider. WPF ScrollBar,
384
11. ,
RangeBase, ,
. ScrollViewer,
5.
ProgressBar
,
ProgressBar.
- , ProgressBar
, - .
. (, ,
!) .11.20 ,
WPF ProgressBar .
FAQ
ProgressBar ,
- ?
Windows Vista, Win32
( ) / (
). , WPF ProgressBar
. ,
, 14 , , .
385
Slider
Slider () , ProgressBar,
,
. .11.21.
.11.22. Slider
.11.23. Slider
Slider
, .11.23.
IsSelectionRangeEnabled true, SelectionStart Selection
End .
,
, ,
.
, Windows Media Player,
, .
386
11. ,
WPF4 ,
: Calendar DatePicker.
WPF ,
.
Calendar
Calendar, . 11.24,
, Windows.
DisplayMode .
, ,
(Month) (Year) (Decade),
. Win
dows, WPF Calendar ,
, ,
.
Month ( )
Year
Decade
387
MultipleRange ,
SelectedDates.
None .
, Calendar,
DisplayDateStart / DisplayDateEnd ( DateTime). .11.25
, DisplayMode.
,
Month 44 .
Month ( )
Year
Decade
,
, . BlackoutDates,
CalendarDateRange. . 11.26 ,
, BlackoutDates :
<Calendar>
<Calendar.BlackoutDates>
<CalendarDateRange Start="4/1/2012" End="4/19/2012"/>
<CalendarDateRange Start="5/1/2012" End="5/5/2012"/>
</Calendar.BlackoutDates>
</Calendar>
Month.
.11.26. , BlackoutDates
CalendarDateRanges
388
11. ,
BlackoutDates CalendarBlackoutDatesCollection,
ObservableCollection<CalendarDateRange>.
AddDatesInPast. ,
.
, CalendarDateRange, DateTime.
MinValue (1 0001) Start DateTime.Today
End.
FirstDayOfWeek Calendar ,
, , ,
System.DayOfWeek,
. Calendar ,
: DisplayDateChanged, DisplayMode
Changed, SelectionModeChanged SelectedDatesChanged (
, ).
DatePicker
DatePicker ,
TextBox ,
Calendar, .
DatePicker .11.27.
Ca
lendar, DatePicker
. DatePicker , Calendar,
DisplayMode, SelectionMode
.
DisplayMode=Month SelectionMode=SingleDate.
, SelectedDatesChanged DatePicker
389
SelectedDateChanged. -
DatePicker DisplayDateChanged, Calendar.
DatePicker
TextBox
. IsDropDownOpen
,
. CalendarOpened CalendarClosed ,
. Selected
DateFormat , TextBox
. Short,
4/20/2012. Long, Friday,
April 20, 2012. , TextBox,
Text. ,
, DateValidationError.
DatePicker ( DatePickerTextBox,
TextBox)
, -
15.
.
, ,
( )
.
, 14,
.
IV
IV.
12
13
14 , ,
12
12.
.NET Framework
,
. , , , , -
. , WPF
.NET, . WPF
:
.
,
.NET Framework. WPF-
. XAML-
. :
,
:
,
, ( ),
.
, .
394
12.
,
Visual Studio
, . 12.1
logo.jpg.
BuildAction .
, , :
<Content Include="logo.jpg">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
,
, Content, ;
. ,
395
(. ).
,
, ,
.
Embedded Resource!
Resource Embedded
Resource ( Visual Studio Embedded Resource).
, WPF-
. Resource
WPF, EmbeddedResource WPF (
Windows Forms).
WPF,
(. ), ,
Content Resource.
, , Content
Resource, XAML-, ,
EmbeddedResource, (
, ).
( Reso
urce), , ,
, ,
.
( , HTML-, ),
Content.
, Resource,
,
Content,
- , WPF
, XAML,
(URI). ,
URI XAML- ,
.
Photo Gallery
7 .
XAML ,
Resource:
396
12.
, XAML- ,
GIF- Content, Reso
urce ( ,
). GIF- ,
.
XAML-
,
!
, XAML-,
,
:
<Image Height="21" Source="slideshow.gif"/>
, ,
, . ()
, :
<Image Height="21" Source="C:\Users\Adam\Documents\slideshow.gif"/>
, , :
<Image Height="21" Source="pack://siteOfOrigin:,,,/slideshow.gif"/>
, ,
Image - , ,
URI, . .12.1
URI XAML-. ,
.
, .12.1 ,
. ,
( ),
XAML-.
397
logo.jpg
,
XAML- (
,
Content)
A/B/logo.jpg
(A\B),
,
A\B
XAML- (
,
Content)
c:\temp\logo.jpg
c:\
temp
file://c:/temp/logo.jpg
c:\temp
\\pc1\images\logo.jpg
\\pc1\images
http://adamnathan.net/logo.jpg
- adamna
than.net
/MyDll;Component/logo.jpg
MyDll.dll
MyDll.exe
/MyDll;Component/A/B/logo.jpg
MyDll.dll
MyDll.exe
(A\B),
pack://siteOfOrigin:,,,/logo.jpg
pack://siteOfOrigin:,,,/A/B/logo.jpg
A\B
FAQ
?
. 12.1 ,
, - .
, ,
, .
,
.
398
12.
,
, .
, , logo.jpg images Visual Stu
dio;
<Resource Include="images\logo.jpg"/>
<Content Include="images\logo.jpg"/>
, logo.jpg
images ,
:
<Image Source="images\logo.jpg"/>
.12.1
.
, , ,
(site of origin).
,
,
, ( ,
),
. .12.1, URI
/AssemblyReference;Component/ResourceName
AssemblyReference , Component
, . ResourceName (
).
AssemblyReference
.NET:
( ).
, AssemblyReference:
AssemblyName
AssemblyName;vVersionNumber ( v )
AssemblyName;PublicKeyToken
AssemblyName;vVersionNumber;PublicKeyToken
(URL)
,
. (
.)
399
:
,
Windows, .
ClickOnce-
URL UNC-, .
XBAP- ClickOnce-
URL UNC- , .
XAML-, ,
.
.
, ,
! pack://siteOf
Origin:,,,/, (,
). , siteOfOrigin , ,
, .
FAQ
?
URI pack XML Paper Specification
(XPS), http://microsoft.com/whdc/xps/xpsspec.
mspx. :
pack://packageURI/partPath
packageURI URI ,
. packageURI
XPS-, file:///C:/Document.xps,
file:,,,C:,Document.xps. WPF-
, URI,
:
siteOfOrigin:/// ( siteOfOrigin:,,,)
application:/// ( application:,,,)
, ,
! (,
/ .)
application:/// ,
.12.1, , siteOfOrigin. (
, WPF
IUriContext. BaseUri,
URI.) , URI,
XAML-:
logo.jpg
400
12.
pack://application:,,,/logo.jpg
URI:
/MyDll;Component/logo.jpg
pack://application:,,,/MyDll;Component/logo.jpg
XAML
URI, .
URI C#
XAML ,
.12.1. URI URI
pack URL.
, Source Image
logo.jpg:
Image image = new Image();
image.Source = new BitmapImage(new Uri("pack://application:,,,/logo.jpg"));
System.Windows.Media.Imaging.BitmapImage
( ,
JPEG, PNG, GIF BMP),
ImageSource ( Source). URI
System.Uri.
pack://application:,,,/ ,
,
Resource Content. ,
, ,
URI siteOfOrigin.
,
, (
),
. , , ,
,
. LocBaml, Windows
SDK, ,
XAML
. LocBaml
.
401
,
UICulture. Visual Studio ,
,
.
Visual Studio.
(
). ,
Edit ().
UICulture Pro
pertyGroup, ,
(Debug, Release ..), ,
,
.
(
):
<Project ...>
<PropertyGroup>
<UICulture>en-US</UICulture>
...
,
en-US,
AssemblyName.resources.dll.
NeutralResourcesLanguage
, :
[assembly: NeutralResourcesLanguage("en-US",
UltimateResourceFallbackLocation.Satellite)]
Uid
XAML (x:Uid) , .
. , , ,
MSBuild :
msbuild /t:updateuid ProjectName.csproj
402
12.
XAML-
x:Uid .
Build,
, .
LocBaml
, Uid,
LocBaml Windows SDK .resources,
( obj\debug):
LocBaml /parse ProjectName.g.en-US.resources /out:en-US.csv
CSV-,
, .
, (
!). LocBaml
, CSV-
! , CSV-
, fr-CA.csv,
LocBaml :
LocBaml /generate ProjectName.resources.dll /trans:fr-CA.csv /cul:fr-CA
,
, , (
fr-CA).
,
System.Threading.Thread.CurrentThread.CurrentUICulture (System.Threading.Thread.
CurrentThread.CurrentCulture) CultureInfo.
WPF WPF,
Silverlight.
,
,
. ( XAML-, ,
XAML,
.)
.NET,
Resources. ,
.
Resources ( System.Windows.ResourceDictionary)
FrameworkElement FrameworkContentElement, ,
WPF.
(. 14 , , )
(. 13 ).
Brush.
403
12.1 Window,
Photo
Gallery.
Brush Background BorderBrush Button (
Window). .12.2.
.12.2. 12.1
12.1.
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Simple Window" Background="Yellow">
<DockPanel>
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal"
HorizontalAlignment="Center">
<Button Background="Yellow" BorderBrush="Red" Margin="5">
<Image Height="21" Source="zoom.gif"/>
</Button>
<Button Background="Yellow" BorderBrush="Red" Margin="5">
<Image Height="21" Source="defaultThumbnailSize.gif"/>
</Button>
<Button Background="Yellow" BorderBrush="Red" Margin="5">
<Image Height="21" Source="previous.gif"/>
</Button>
<Button Background="Yellow" BorderBrush="Red" Margin="5">
<Image Height="21" Source="slideshow.gif"/>
</Button>
<Button Background="Yellow" BorderBrush="Red" Margin="5">
<Image Height="21" Source="next.gif"/>
</Button>
<Button Background="Yellow" BorderBrush="Red" Margin="5">
<Image Height="21" Source="counterclockwise.gif"/>
</Button>
<Button Background="Yellow" BorderBrush="Red" Margin="5">
<Image Height="21" Source="clockwise.gif"/>
</Button>
<Button Background="Yellow" BorderBrush="Red" Margin="5">
<Image Height="21" Source="delete.gif"/>
</Button>
</StackPanel>
<ListBox/>
404
12.
</DockPanel>
</Window>
Window .
.
(CSS)
-,
.
, ,
, ,
. 12.2
.
12.2.
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Simple Window">
<Window.Resources>
<SolidColorBrush x:Key="backgroundBrush">Yellow</SolidColorBrush>
<SolidColorBrush x:Key="borderBrush">Red</SolidColorBrush>
</Window.Resources>
<Window.Background>
<StaticResource ResourceKey="backgroundBrush"/>
</Window.Background>
<DockPanel>
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal"
HorizontalAlignment="Center">
<Button Background="{StaticResource backgroundBrush}"
BorderBrush="{StaticResource borderBrush}" Margin="5">
<Image Height="21" Source="zoom.gif"/>
</Button>
<Button Background="{StaticResource backgroundBrush}"
BorderBrush="{StaticResource borderBrush}" Margin="5">
<Image Height="21" Source="defaultThumbnailSize.gif"/>
</Button>
<Button Background="{StaticResource backgroundBrush}"
BorderBrush="{StaticResource borderBrush}" Margin="5">
<Image Height="21" Source="previous.gif"/>
</Button>
<Button Background="{StaticResource backgroundBrush}"
BorderBrush="{StaticResource borderBrush}" Margin="5">
<Image Height="21" Source="slideshow.gif"/>
</Button>
<Button Background="{StaticResource backgroundBrush}"
BorderBrush="{StaticResource borderBrush}" Margin="5">
<Image Height="21" Source="next.gif"/>
</Button>
<Button Background="{StaticResource backgroundBrush}"
405
x:Key
ResourceDictionary 2 XAML.
StaticRe
source ( System.Windows.StaticResourceExtension).
Window.Background , But
ton.Background Button.BorderBrush .
Brush, ,
.
12.2 -
,
.12.2.
, XAML- ( ,
). ,
backgroundBrush - :
<LinearGradientBrush x:Key="backgroundBrush" StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="Blue" Offset="0"/>
<GradientStop Color="White" Offset="0.5"/>
<GradientStop Color="Red" Offset="1"/>
</LinearGradientBrush>
, .12.3.
.12.3. , 12.2,
backgroundBrush -
406
12.
StaticResource
.
.
.
.
Resources ( ). ,
..,
. Resources Application.
,
(. 14). ,
( ,
). ,
InvalidOperationException.
,
,
. , ,
,
.
, ,
, .
!
7 , WPF-
.
.
, Freezable
, x:Shared=false,
, .
WPF :
StaticResource ,
( )
DynamicResource
,
DynamicResource (System.Windows.DynamicResourceExtension)
, StaticResource,
407
DynamicResource StaticResource .
, ; , ,
, .
-
StaticResource, DynamicResource, ,
.
StaticResource DynamicResource ,
,
DynamicResource.
(,
), .
StaticResource DynamicResource
. , DynamicResource
,
. , DynamicResource
. , StaticResource,
Window Page,
DynamicResource , .
, DynamicResource
, StaticResource . , Static
Resource ,
! Window:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
...
<Image Height="21" Source="zoom.gif"/>
...
</Window>
:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<Image x:Key="zoom" Height="21" Source="zoom.gif"/>
</Window.Resources>
<StackPanel>
<StaticResource ResourceKey="zoom"/>
</StackPanel>
</Window>
, Image, ,
XAML- ,
. Image
, Visual (, ,
408
12.
),
. , ,
StaticResource XAML-,
"Specified Visual is already a child of another
Visual or the root of a CompositionTarget" ( Visual
Visual
CompositionTarget).
XAML-
XAML-
,
XAML-.
XAML- ,
( ,
), MergedDictionaries
ResourceDictionary.
, Window
Resources, , :
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="file1.xaml"/>
<ResourceDictionary Source="file2.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
ResourceDictionary .
, file1.xaml :
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Image x:Key="logo" Source="logo.jpg"/>
</ResourceDictionary>
,
( ,
).
, XAML-
(. 20
).
#include,
C C++, XAML .
409
. StaticResource XAML
. ,
XAML-. ,
StaticResource ,
(
)! DynamicReso
urce .
- Window 12.2
Background .
, , .
DynamicResource ,
,
, :
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Simple Window" Background="{DynamicResource backgroundBrush}">
<Window.Resources>
<SolidColorBrush x:Key="backgroundBrush">Yellow</SolidColorBrush>
<SolidColorBrush x:Key="borderBrush">Red</SolidColorBrush>
</Window.Resources>
...
</Window>
, ,
. .
x:Shared="False",
,
.
,
Image (
, Visual).
,
. x:Shared="False"
,
. :
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<Image x:Shared="False" x:Key="zoom" Height="21" Source="zoom.gif"/>
</Window.Resources>
<StackPanel>
<!-- ! -->
410
12.
<StaticResource ResourceKey="zoom"/>
<StaticResource ResourceKey="zoom"/>
<StaticResource ResourceKey="zoom"/>
</StackPanel>
</Window>
, x:Shared
XAML-. XAML-
.
,
XAML-, ,
. . ,
Window window, SolidColorBrush,
12.2, C# :
window.Resources.Add("backgroundBrush", new SolidColorBrush(Colors.Yellow));
window.Resources.Add("borderBrush", new SolidColorBrush(Colors.Red));
.
StaticResource DynamicResource ,
C# .
, StaticResource,
FindResource (
FrameworkElement FrameworkContentElement).
, Button ( ,
12.2):
<Button Background="{StaticResource backgroundBrush}"
BorderBrush="{StaticResource borderBrush}"/>
C# ( , StackPanel,
Button, stackPanel):
Button button = new Button();
// , Button Window:
stackPanel.Children.Add(button);
button.Background = (Brush)button.FindResource("backgroundBrush");
button.BorderBrush = (Brush)button.FindResource("borderBrush");
FindResource , ,
TryFindResource,
null.
DynamicResource SetResourceReference
( FrameworkElement FrameworkContentElement)
.
, StaticResource Dyna
micResource:
411
C#:
Button button = new Button();
button.SetResourceReference(Button.BackgroundProperty, "backgroundBrush");
button.SetResourceReference(Button.BorderBrushProperty, "borderBrush");
, Button -
Window (
). , StaticResource,
.
StaticResource
. FindResource TryFindResource
,
. , SetRe
sourceReference , .
,
,
. , Background BorderBrush
( , Window
window):
Button button = new Button();
button.Background = (Brush)window.Resources["backgroundBrush"];
button.BorderBrush = (Brush)window.Resources["borderBrush"];
StaticResource XAML
( FindResource ) ,
.
,
.
XAML ,
.
XAML .
,
DynamicResource, ,
System.Windows: Sys
temColors, SystemFonts SystemParameters. ,
,
.
412
12.
XAML:
<Button Background="SystemColors.WindowBrush"/>
C#:
.
BrushConverter
button.Background = (Brush)new
BrushConverter().ConvertFrom("SystemColors.WindowBrush");
XAML:
<Button Background="{x:Static SystemColors.WindowBrush}"/>
C#:
button.Background = SystemColors.WindowBrush;
XAML:
<Button Background=
"{StaticResource SystemColors.WindowBrushKey}"/>
C#:
button.Background =
(Brush)FindResource("SystemColors.WindowBrushKey");
XAML:
<Button Background=
"{StaticResource {x:Static SystemColors.WindowBrush}}"/>
C#:
button.Background =
(Brush)FindResource(SystemColors.WindowBrush);
,
,
,
Brush
"System
Colors.WindowBrush
Key",
,
SystemColors.Window
Brush
,
413
XAML:
.
<Button Background=
"{StaticResource {x:Static SystemColors.WindowBrushKey}}"/> , ,
,
C#:
button.Background =
(
(Brush)FindResource(SystemColors.WindowBrushKey);
),
,
XAML:
.
<Button Background=
"{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
,
C#:
,
button.SetResourceReference(
Button.BackgroundProperty, SystemColors.WindowBrushKey);
WPF, ,
, .
,
!
,
( , )
.
. ,
, ,
,
XAML-, .
, ,
,
(. 14).
Binding
: Twitter
XAML
13
13.
WPF
.NET.
, .
-, XML-, -,
, WPF, Button.
.NET.
(, ListBox DataGrid) ,
XML-, .
ListBoxItem ListBox, : ,
ListBox! - . ,
. , .
.
Binding
System.Win
dows.Data.Binding,
. Binding
.
Binding
, Photo Gallery,
, TextBlock,
, ListBox:
Binding
415
SelectedItem TreeView:
void treeView_SelectedItemChanged(object sender,
RoutedPropertyChangedEventArgs<object> e)
{
currentFolder.Text = (treeView.SelectedItem as TreeViewItem).Header.ToString();
Refresh();
}
, Binding,
, Main
Window:
public MainWindow()
{
InitializeComponent();
Binding binding = new Binding();
// -
binding.Source = treeView;
// -
binding.Path = new PropertyPath("SelectedItem.Header");
// -
currentFolder.SetBinding(TextBlock.TextProperty, binding);
}
currentFolder.Text
treeView.SelectedItem.Header.
TreeView , Header (
Photo Gallery ),
( - ) ,
( ). ,
.
,
!
.
, ,
.
Binding - -
. - ( treeView.SelectedItem.Header)
: - Source
( ,
), PropertyPath, Path.
Binding - ( currentFolder.
Text) Binding, SetBinding (
416
13.
FrameworkElement FrameworkContentElement),
Binding.
Binding
. SetBinding Framework
Element FrameworkContentElement, .
SetBinding BindingOperations.
, , ,
-:
BindingOperations.SetBinding(currentFolder, TextBlock.TextProperty, binding);
, Depen
dencyObject,
, FrameworkElement, FrameworkContentElement (,
Freezable).
Binding
, Binding
,
BindingOperations.ClearBinding. (,
.) - . :
BindingOperations.ClearBinding(currentFolder, TextBlock.TextProperty);
- Binding,
, BindingOperations.ClearAllBindings:
BindingOperations.ClearAllBindings(currentFolder);
-
, :
currentFolder.Text = "I am no longer receiving updates.";
. (
Binding .)
ClearBinding ,
( ,
..). , ,
, 3 WPF.
Binding, SetBinding, ,
, ClearBinding
, ClearValue
. ( ClearBinding
ClearValue -!)
Binding
417
Binding XAML
SetBinding XAML- , WPF
, Binding
. Binding
( , Extension).
Binding XAML, -
,
. ,
currentFolder:
<TextBlock x:Name="currentFolder" DockPanel.Dock="Top"
Text="{Binding ElementName=treeView, Path=SelectedItem.Header}"
Background="AliceBlue" FontSize="16" />
, ,
?
, .
Binding ,
Path. ,
-, Path ,
. , XAML
:
<TextBlock x:Name="currentFolder" DockPanel.Dock="Top"
Text="{Binding SelectedItem.Header, ElementName=treeView}"
Background="AliceBlue" FontSize="16" />
,
. ,
Path .
, XAML- -
ElementName, Source, .
, ElementName XAML,
-. ,
WPF4 x:Reference Source
:
<TextBlock x:Name="currentFolder" DockPanel.Dock="Top"
Text="{Binding Source={x:Reference TreeView}, Path=SelectedItem.Header}"
Background="AliceBlue" FontSize="16" />
418
13.
TargetNullValue Binding
, , -
null. ,
, Nothing is selected. ( )
, - null:
<TextBlock Text="{Binding ... TargetNullValue=Nothing is selected.}" .../>
TargetNullValue ,
- - null.
RelativeSource Binding
Relative
Source Binding, , . RelativeSource,
.
RelativeSource.
- -:
{Binding RelativeSource={RelativeSource Self}}
- TemplatedParent -
( ):
{Binding RelativeSource={RelativeSource TemplatedParent}}
- -
, :
{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type desiredType}}}
- n- , :
{Binding RelativeSource={RelativeSource FindAncestor,
AncestorLevel=n, AncestorType={x:Type desiredType}}}
- ,
:
{Binding RelativeSource={RelativeSource PreviousData}}
RelativeSource
, .
RelativeSource Self
.
Slider, ToolTip
:
<Slider ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=Value}"/>
Binding
419
.NET
TreeView TextBox ,
. 3
,
. WPF
- -.
WPF
.NET . , ,
Photo Gallery Label,
.
Count (
Photos), Content Count :
<Label x:Name="numItemsLabel"
Content="{Binding Source={StaticResource photos}, Path=Count}"
DockPanel.Dock="Bottom"/>
( , ,
XAML Source. ElementName
,
FrameworkElement FrameworkContentElement!) .13.1
. , 54,
- 54 item(s). ,
item(s).
, .
.13.1.
photos.Count
.NET
.
,
. , , .13.1,
, , , .
, -
:
System.ComponentModel.INotifyPropertyChanged,
PropertyChanged.
XXXChanged, XXX ,
.
420
13.
, WPF .
( XXXChanged WPF
.) Photo Gallery
, photos INotifyPropertyChanged.
(Add, Remove, Clear,
Insert) PropertyChanged. , .NET Framework
, ! Observ
ableCollection. , photos.Count
public class Photos : Collection<Photo>
:
public class Photos : ObservableCollection<Photo>
.NET
-,
.NET, WPF . -
ICustomTypeDescriptor, WPF (,
, TypeDescriptionProvider,
), , Pro
pertyDescriptor .
, ,
(,
).
-!
-
.NET, - . -
. ,
( ) , .
-
-, , - ( Path
Binding) ! -
.
? .13.2 , .13.1,
Path:
Binding
421
<Label x:Name="numItemsLabel"
Content="{Binding Source={StaticResource photos}}"
DockPanel.Dock="Bottom"/>
.13.2.
photos
photos UIElement,
, ToString.
,
, , , ,
ListBox, .
, XAML-
, ,
, .
, Photo Gallery Popup,
zoomButton. Placement Place
mentTarget Popup,
UIElement. C# :
Button zoomButton = new Button();
...
Popup zoomPopup = new Popup();
zoomPopup.Placement = PlacementMode.Center;
zoomPopup.PlacementTarget = zoomButton;
.
, x:Reference, WPF4,
Binding.
422
13.
UIElement!
- UIElement,
, ,
. , XAML-
InvalidOperationException "Specified element is already the
logical child of another element" (
):
<Label x:Name="one" Content="{Binding ElementName=two}"/>
<Label x:Name="two" Content="text"/>
, Label TextBlock
(, , Content Text):
<TextBlock x:Name="one" Text="{Binding ElementName=two}"/>
<Label x:Name="two" Content="text"/>
photos.Count ,
ListBox (
Window) photos. Photo Gallery .
,
ListBox, ,
. ListBox
ListBoxItem .
,
- ( FileSystem
Watcher), ListBox.
,
.
Binding,
- ListBox.Items, , , Items
. ListBox,
ItemsSource,
Binding
423
. IEnumerable,
photos Binding :
<ListBox x:Name="pictureBox"
ItemsSource="{Binding Source={StaticResource photos}}" ...>
...
</ListBox>
- ( ), -
INotifyCollectionChanged.
ObservableCollection INotifyPropertyChanged
InotifyCollectionChanged , ,
Photos ObservableCollection<Photo>, ,
.
.13.3 .
, pho
tos , ToString, .
DisplayMemberPath,
(. 10).
ItemsSource.
,
.
424
13.
Photo ,
, ToString ,
Name .
.13.4. DisplayMemberPath
,
,
Photo Image DisplayMemberPath.
,
-. ( ,
- . ,
, WPF
!) (
) ,
.
.
Binding
425
10 , Selector,
ListBox, .
( ,
IEnumerable), WPF ,
-, ,
, .
/ ( , , )
, .
, true
IsSynchronizedWithCurrentItem ( ).
XAML- ListBox,
photos:
<ListBox IsSynchronizedWithCurrentItem="True" DisplayMemberPath="Name"
ItemsSource="{Binding Source={StaticResource photos}}"></ListBox>
<ListBox IsSynchronizedWithCurrentItem="True" DisplayMemberPath="DateTime"
ItemsSource="{Binding Source={StaticResource photos}}"></ListBox>
<ListBox IsSynchronizedWithCurrentItem="True" DisplayMemberPath="Size"
ItemsSource="{Binding Source={StaticResource photos}}"></ListBox>
IsSynchronizedWithCurrentItem="True"
-,
.
(, ,
!) .13.5 , . -
IsSynchronizedWithCurrentItem false,
426
13.
.
.
IsSynchronizedWithCurrentItem
!
Selector ( ,
SelectionMode ListBox Multiple Extended),
,
!
.13.5.
DataContext
- , , -
( photos).
- (
- , - )
. WPF
, Binding Source,
RelativeSource ElementName.
.
-, photos,
, -
DataContext -. (
, FrameworkElement FrameworkContentElement,
DataContext Object.) Binding,
- , WPF ,
null DataContext.
Binding
427
, Label ListBox
-, DataContext :
<StackPanel DataContext="{StaticResource photos}">
<Label x:Name="numItemsLabel"
Content="{Binding Path=Count}" .../>
...
<ListBox x:Name="pictureBox" DisplayMemberPath="Name"
ItemsSource="{Binding}" ...>
...
</ListBox>
...
</StackPanel>
DataContext ,
,
- :
parent.DataContext = photos;
XAML , {Binding},
, , -
-
, .
FAQ
- ,
Binding?
, . -
-, ,
. -
, , ,
.
, -
, , - .
Binding
. ,
, .
, ;
. (,
RelativeSource
, .)
428
13.
, - , ,
, .
.
, !
,
(
Photo Gallery). WPF
,
, ,
. :
, .
,
StringFormat Binding.
, WPF String.Format,
StringFormat (format) -
(args[0]). , {0}
-,
, {0:C}
, {0:P} , {0:X}
.
, .13.1 54 item(s),
54, TextBlock Bin
ding StringFormat:
<TextBlock x:Name="numItemsLabel"
Text="{Binding StringFormat={}{0} item(s),
Source={StaticResource photos}, Path=Count}"
DockPanel.Dock="Bottom"/>
{} ,
{ . (. 2
XAML),
. {} , Binding
( ) :
<TextBlock x:Name="numItemsLabel" DockPanel.Dock="Bottom">
<TextBlock.Text>
<Binding Source="{StaticResource photos}" Path="Count">
<Binding.StringFormat>{0} item(s)</Binding.StringFormat>
</Binding>
</TextBlock.Text>
</TextBlock>
429
StringFormat , - !
StringFormat ,
Binding , -
string. Content
Label , Object:
<Label x:Name="numItemsLabel"
Content="{Binding StringFormat={}{0} item(s),
Source={StaticResource photos}, Path=Count}"
DockPanel.Dock="Bottom"/>
, , {:
<TextBlock x:Name="numItemsLabel"
Text="{Binding StringFormat=Number of items: {0},
Source={StaticResource photos}, Path=Count}"
DockPanel.Dock="Bottom"/>
, N0,
. ,
Count 54, 54 item(s), Count 1001,
1,001 item(s) ( , en-US):
<TextBlock x:Name="numItemsLabel"
Text="{Binding StringFormat={}{0:N0} item(s),
Source={StaticResource photos}, Path=Count}"
DockPanel.Dock="Bottom"/>
System.Xaml {}
!
System.Xaml, WPF 4, , -
{}
. System.Xaml {}
(
),
. , XAML-
System.Xaml :
<TextBlock Text="{Binding StringFormat={}{0:C}}" />
430
13.
, System.Xaml
(, XAML-),
. ,
, , :
<TextBlock Text="{Binding StringFormat=\{0:C\}}" />
XXXStringFormat,
XXX . ,
ContentStringFormat, Content,
ItemStringFormat,
. .13.1 ,
.
13.1. , WPF
StringFormat
BindingBase
ContentStringFormat
ItemStringFormat
ItemsControl, HierarchicalDataTemplate
HeaderStringFormat
HeaderedContentControl, HeaderedItemsControl,
DataGridColumn, GridViewColumn, GroupStyle
ColumnHeaderStringFormat
GridView, GridViewHeaderRowPresenter
Label TextBlock,
StringFormat Binding,
Label ContentStringFormat, Label
:
<Label x:Name="numItemsLabel" ContentStringFormat="{}{0} item(s)"
Content="{Binding Source={StaticResource photos}, Path=Count}"
DockPanel.Dock="Bottom"/>
. .13.6
ListBox
: :
<ListBox ItemStringFormat="{}{0:C}"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:Int32>-9</sys:Int32>
<sys:Int32>9</sys:Int32>
<sys:Int32>1234</sys:Int32>
<sys:Int32>1234567</sys:Int32>
</ListBox>
431
(USA)
.13.6. ListBox
,
.NET .
WPF ( DataTemp
late) . , ContentControl
ContentTemplate
Content, ItemsControl ItemTemplate,
.
.13.2. , XXXTemplate , XXXStringFormat.
13.2. DataTemplate
ContentTemplate
ItemTemplate
ItemsControl, HierarchicalDataTemplate
HeaderTemplate
SelectedContentTemplate
TabControl
DetailsTemplate
DataGridRow
RowDetailsTemplate
DataGrid
RowHeaderTemplate
DataGrid
ColumnHeaderTemplate
GridView, GridViewHeaderRowPresenter
CellTemplate
DataGridTemplateColumn, GridViewColumn
CellEditingTemplate
DataGridTemplateColumn
DataTemplate,
. DataTemplate,
ItemsPanelTemplate, 10,
FrameworkTemplate. VisualTree,
FrameworkElement.
XAML, .
432
13.
.13.7 , . ,
- placeholder.jpg, -
!
.13.7. -
, Image ,
Source FullPath Photo? ,
!
( -).
ItemTemplate,
ItemsSource. ,
.13.8, :
<ListBox x:Name="pictureBox"
ItemsSource="{Binding Source={StaticResource photos}}" ...>
433
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Path=FullPath}" Height="35"/>
</DataTemplate>
</ListBox.ItemTemplate>
...
</ListBox>
.13.8.
, ,
. ,
. ,
DataType .
, , DataTemplate Resources
Window,
, , ,
: , - .
DataTemplate Resources
Application, .
,
(, ListBox, ),
,
.
434
13.
DataTemplate
, XML-
, HierarchicalDataTemplate.
,
, , TreeView Menu.
XmlDataProvider
HierarchicalDataTemplate XML-.
.
, WPF ,
, (
) ,
. , Data
TemplateSelector, SelectTemplate.
,
XXXTemplateSelector.
XXXTemplate, .13.2,
XXXTemplateSelector (.13.3).
13.3. ,
ContentTemplateSelector
ItemTemplateSelector
ItemsControl, HierarchicalDataTemplate
HeaderTemplateSelector
HeaderedContentControl, HeaderedItemsControl,
DataGridRow, DataGridColumn, GridViewColumn,
GroupStyle
SelectedContentTemplateSelector TabControl
DetailsTemplateSelector
DataGridRow
RowDetailsTemplateSelector
DataGrid
RowHeaderTemplateSelector
DataGrid
ColumnHeaderTemplateSelector
GridView, GridViewHeaderRowPresenter
CellTemplateSelector
DataGridTemplateColumn, GridViewColumn
CellEditingTemplateSelector
DataGridTemplateColumn
-,
435
, ,
. ,
.
,
. ,
,
Brush, ,
Microsoft Excel.
, .
.
, ( Background)
photos (
Count). ,
Background , Brush:
<Label Background="{Binding Path=Count, Source={StaticResource photos}}" .../>
,
Converter:
<Label Background="{Binding Path=Count, Converter={StaticResource myConverter},
Source={StaticResource photos}}" .../>
, ,
Brush, :
<Window.Resources>
<local:CountToBackgroundConverter x:Key="myConverter"/>
</Window.Resources>
CountToBackgroundConverter,
IValueConverter ( System.Win
dows.Data). : Convert,
-, -, Con
vertBack, .
, C# CountToBackgroundConverter
:
public class CountToBackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (targetType != typeof(Brush))
throw new InvalidOperationException("The target must be a Brush!");
// , Parse
int num = int.Parse(value.ToString());
436
13.
Convert .
, Brush
es.Yellow, , Brushes.Transparent
. ( , ,
.) ConvertBack ,
. VI
, ConvertBack. .13.9
.
.13.9.
, photos
. CountToBack
groundConverter, , , IntegerToBrushConverter,
, ,
Brush. ,
, . (,
, - Foreground (
) Transparent ()!) , ,
.
437
Culture. , Brushes.Yellow
CountToBackgroundConverter.Convert,
:
return (num == 0 ? parameter : Brushes.Transparent);
, parameter :
<Label Background="{Binding Path=Count, Converter={StaticResource myConverter},
ConverterParameter=Yellow, Source={StaticResource photos}}" Content="..." />
ConverterParameter "Yellow" ,
.
, "Yellow" ,
ConverterParameter (Object). , Convert
"Yellow", Brush. Convert
parameter , , num ,
.
, Back
ground Label .
ConverterCulture ,
(IETF),
"ko-KR", CultureInfo.
WPF
. BooleanTo
VisibilityConverter Visibility (
Visible, Hidden, Collapsed) Boolean,
null (). true
Visible, false null Collapsed. Visible
true, Hidden Collapsed false.
. , XAML-
Show Status Bar ( )
:
<Window.Resources>
<BooleanToVisibilityConverter x:Key="booltoVis"/>
</Window.Resources>
...
<CheckBox x:Name="checkBox">Show Status Bar</CheckBox>
...
<StatusBar Visibility="{Binding ElementName=checkBox, Path=IsChecked,
Converter={StaticResource booltoVis}}">...</StatusBar>
StatusBar ,
IsChecked CheckBox true.
438
13.
!
, WPF
,
, ,
( ).
, ,
. Visual Studio
Output (). Visual Studio 2010 Ultimate
IntelliTrace.
(
Background photos.Count)
:
System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid
for target property.; Value='39' BindingExpression:Path=Count; DataItem='Photos'
(HashCode=58961324); target element is 'Label' (Name='numItemsLabel'); target
property is 'Background' (type 'Brush')
, - (
) ,
!
System.Diagnostics.Tra
ceSource,
. (Mike Hillberg), WPF,
http://blogs.msdn.com/mikehillberg/archi
ve/2006/09/14/WpfTraceSources.aspx. ,
WPF (
), ,
, .
PresentationTraceSources.TraceLevel (
System.Diagnostics WindowsBase),
Binding
, .
PresentationTraceLevel: None, Low, Medium,
High.
,
.
Content numItemsLabel Count photos (.
. 13.1), ,
, , .
StringFormat,
, item(s). ( , ,
1 item(s) .)
439
,
1 item ( ), 2 items (
). RawCountToDescriptionConverter:
public class RawCountToDescriptionConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
// , Parse
int num = int.Parse(value.ToString());
return num + (num == 1 ? " item" : " items");
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
, ,
(, ,
culture).
, .
-
- ,
IValueConverter.
,
, Binding.DoNothing.
, null, null
-.
Binding.DoNothing : ,
, Binding .
- ,
(, ..). Binding.DoNothing
Convert ConvertBack,
Binding (, ClearBinding),
-.
440
13.
FAQ
, ?
ItemTemplate ItemsControl,
Binding,
.
Binding ItemsControl, -
Convert (
). ,
,
.
, , ,
( IsSynchronizedWithCurrentItem
true) , ,
-,
. ,
, (
!). -
,
?
. ( ,
IEnumerable),
. (
, ICollectionView)
, ,
, .
, ,
-.
-,
. (,
) .
ICollectionView SortDescriptions,
.
441
, ,
, (, Name,
DateTime Size Photo), ,
: .
SortDescription,
ListSortDirection. :
SortDescription sort = new SortDescription("Name", ListSortDirection.Ascending);
SortDescriptions SortDescription.
,
. SortDescription
, .
, SortDescrip
tion, DateTime ,
, Name (
):
view.SortDescriptions.Add(new SortDescription("DateTime",
ListSortDirection.Descending));
view.SortDescriptions.Add(new SortDescription("Name",
ListSortDirection.Ascending));
SortDescriptions Clear,
. ,
, , , !
13.1 , Photo Gallery
Name, DateTime Size,
. Windows,
.
13.1.
// Click :
void sortByName_Click(object sender, RoutedEventArgs e)
{
SortHelper("Name");
}
void sortByDateTime_Click(object sender, RoutedEventArgs e)
{
SortHelper("DateTime");
}
void sortBySize_Click(object sender, RoutedEventArgs e)
{
SortHelper("Size");
}
void SortHelper(string propertyName)
442
13.
{
//
ICollectionView view = CollectionViewSource.GetDefaultView(
this.FindResource("photos"));
// ,
//
if (view.SortDescriptions.Count > 0
&& view.SortDescriptions[0].PropertyName == propertyName
&& view.SortDescriptions[0].Direction == ListSortDirection.Ascending)
{
// ,
//
view.SortDescriptions.Clear();
view.SortDescriptions.Add(new SortDescription(
propertyName, ListSortDirection.Descending));
}
else
{
//
view.SortDescriptions.Clear();
view.SortDescriptions.Add(new SortDescription(
propertyName, ListSortDirection.Ascending));
}
}
, ListBox,
. , ,
- photos,
CollectionViewSource.GetDefaultView.
-
,
.
,
ICollectionView.SortDescriptions ( ),
.
IList ( ), ICollec
tionView, CollectionViewSource.GetDefaultView,
ListCollectionView. ICol
lectionView ListCollectionView, ,
IComparer, CustomSort.
ICom
parer.Compare. Compare
.
443
ICollectionView GroupDescriptions,
, SortDescriptions.
PropertyGroupDescription
, , .
, photos
DateTime:
//
ICollectionView view = CollectionViewSource.GetDefaultView(
this.FindResource("photos"));
//
view.GroupDescriptions.Clear();
view.GroupDescriptions.Add(new PropertyGroupDescription("DateTime"));
, , ,
,
. ,
GroupStyle GroupStyle.
HeaderTemplate,
, .
ListBox Photo Gallery
GroupStyle:
<ListBox x:Name="pictureBox"
ItemsSource="{Binding Source={StaticResource photos}}" ...>
<ListBox.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="1">
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold"/>
</Border>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListBox.GroupStyle>
...
</ListBox>
.
CollectionViewGroup, .
, ,
Name, , .
, ,
Name . .13.10
444
13.
XAML-
.
,
, ,
GroupStyle, WPF.
GroupStyle.Default XAML
:
<ListBox x:Name="pictureBox"
ItemsSource="{Binding Source={StaticResource photos}}" ...>
<ListBox.GroupStyle>
<x:Static Member="GroupStyle.Default"/>
</ListBox.GroupStyle>
...
</ListBox>
.13.10. ListBox
, , , ,
Photo.DateTime .
DateTime , , ,
, !
,
PropertyGroupDescription,
, .
445
. ,
DateTimeToDateConverter, DateTime
, :
public class DateTimeToDateConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return ((DateTime)value).ToString("MM/dd/yyyy");
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
DateTime. , ,
Convert DateTime:
return ((DateTime)value).Date;
,
,
.. (,
.)
,
:
//
ICollectionView view = CollectionViewSource.GetDefaultView(
this.FindResource("photos"));
//
view.GroupDescriptions.Clear();
view.GroupDescriptions.Add(
new PropertyGroupDescription("DateTime", new DateTimeToDateConverter()));
.13.11.
,
. .
SortDescription ,
. , (
), ,
( ), ,
.
446
13.
.13.11. ,
Photo.DateTime
, .
PropertyGroupDescription,
null. value
- ( Photo
Photo Gallery), .
ICollectionView ,
,
. Filter Predicate<Object> ( ,
, Object
).
Filter null ( ),
-. ,
.
, ( true),
( false).
C# .
, Photo,
DateTime , 7 :
447
-,
:
ICollectionView view = CollectionViewSource.GetDefaultView(this.FindResource
("photos"));
view.Filter = (o) => { return ((o as Photo).DateTime DateTime.Now).Days <= 7;};
, view.Filter null.
,
, 7
. ICollectionView
CurrentItem ( CurrentPosition,
, ),
CurrentItem. Photo Gallery
Click Next Photo ( ) Previous Photo (
):
void previous_Click(object sender, RoutedEventArgs e)
{
//
ICollectionView view = CollectionViewSource.GetDefaultView(
this.FindResource("photos"));
//
view.MoveCurrentToPrevious();
// ,
if (view.IsCurrentBeforeFirst) view.MoveCurrentToLast();
}
void next_Click(object sender, RoutedEventArgs e)
{
//
ICollectionView view = CollectionViewSource.GetDefaultView(
this.FindResource("photos"));
//
view.MoveCurrentToNext();
// ,
if (view.IsCurrentAfterLast) view.MoveCurrentToFirst();
}
448
13.
, .
ListBox, ,
, ,
. , - -
, CurrentItem null, CurrentPosition -1.
, ListBox.
, CurrentPosition ,
CurrentItem .
, Binding,
. ,
Binding
, :
"{Binding Path=/}"
Binding DateTime :
"{Binding Path=/DateTime}"
Binding ,
Photos ,
:
"{Binding Path=Photos/}"
, Binding DateTime
:
"{Binding Path=Photos/DateTime}"
/
.
!
, ,
, IsSynchronizedWithCur
rentItem true. SelectedItem
CurrentItem
. WPF ,
, ,
. , ,
.
449
, ,
,
-. ,
-
. , CollectionViewSource
,
.
.
photos
Photo Gallery, :
CollectionViewSource viewSource = new CollectionViewSource();
viewSource.Source = photos;
// viewSource.View
// ICollectionView,
CollectionViewSource ,
,
XAML-:
<Window.Resources>
<local:Photos x:Key="photos"/>
<CollectionViewSource x:Key="viewSource" Source="{StaticResource photos}"/>
</Window.Resources>
-,
CollectionViewSource,
-, :
<ListBox x:Name="pictureBox"
ItemsSource="{Binding Source={StaticResource photos viewSource}}" ...>
...
</ListBox>
, Collection
ViewSource, WPF CollectionViewSource ,
Path Binding. ,
Count -
Photos, CollectionViewSource.
ListBox , ,
,
.
, , ,
ICollectionView Collection
ViewSource.GetDefaultView, CollectionViewSource.
XAML, CollectionViewSource
SortDescriptions GroupDescriptions,
450
13.
, ICollectionView. ,
Filter, ,
, XAML-. (,
.)
, , XAML
:
<PropertyGroupDescription PropertyName="DateTime"/>
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
SortDescription .NET,
XML,
:
xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"
viewSource_Filter, XAML,
, ; -
:
void viewSource_Filter(object sender, FilterEventArgs e)
{
e.Accepted = ((e.Item as Photo).DateTime DateTime.Now).Days <= 7;
}
, - ,
e.Item.
,
e.Accepted , .
-
,
CollectionViewSource ,
!
451
FAQ
( CollectionViewSource),
?
.
. ,
, , , , ,
.
-!
;
, IsSynchronized
WithCurrentItem false. ,
!
IsSynchronizedWithCurrentItem false, WPF
true, ItemsSource
,
( SelectionMode
Single). , , ,
,
. (- ,
IsSynchronizedWithCurrentItem true
.)
- .NET, ,
,
, Windows, Excel ..
.NET,
! (
,
.)
, WPF
,
: XmlDataProvider ObjectDataProvider.
452
13.
WPF3.5 SP1
Language Integrated Query (LINQ).
Source Binding ( DataContext ) LINQ-
IEnumerable ,
. , LINQ to SQL, LINQ to XML
,
LINQ, WPF,
, XML- ..
XmlDataProvider
XmlDataProvider XML-
, . 13.2
XmlDataProvider XML-
:
13.2. XML-
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="XML Data Binding">
<Window.Resources>
<XmlDataProvider x:Key="dataProvider" XPath="GameStats">
<x:XData>
<GameStats xmlns="">
<! >
<GameStat Type="Beginner">
<HighScore>1203</HighScore>
</GameStat>
XML
<GameStat Type="Intermediate">
<HighScore>1089</HighScore>
</GameStat>
<GameStat Type="Advanced">
<HighScore>541</HighScore>
</GameStat>
</GameStats>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<Grid>
XmlDataProvider
XML-, XData;
453
, XAML-.
( XData, .)
XPath XmlDataProvider XPath-,
, XML. XPath (
XML Path Language) W3C http://www.w3.
org/TR/xpath.
XML- XAML-,
xmlns, 13.2.
,
( http://schemas.microsoft.com/winfx/2006/xaml/presen
tation), XPath- , .
XmlDataProvider ,
, ,
Path Binding,
XPath. 13.2 XPath
HighScore ListBox,
.13.12.
.13.12. XML-
13.2
XML- ( ),
Source XmlDataProvider
(URI),
. URI, ,
, , ..
13.2 XmlDataProvider :
<XmlDataProvider x:Key="dataProvider" XPath="GameStats" Source="GameStats.xml"/>
XPath , ,
. , 13.2
XPath "GameStat/@Type",
ListBox Type GameStat (Beginner, Interme
diate Advanced). "comment()",
XML-!
454
13.
XPath Path
XPath Path
Binding. XML- XmlDataProvider ,
System.Xml.dll ( System.Xml),
XmlNode. ,
, , Path Binding
XmlNode XmlNodeList. ,
OuterXml XmlNode
Label <HighScore>1203</HighScore>,
1203:
<Label Content="{Binding Source={StaticResource dataProvider},
XPath=GameStat/HighScore, Path=OuterXml}"/>
DisplayMemberPath ItemsControl
Path, XPath.
XML- ,
(TreeView Menu) ,
HierarchicalDataTemplates.
13.3, 13.2,
( HierarchicalDataTemplates
DataTemplate), ListBox TreeView, XPath
XML-.
13.3. HierarchicalDataTemplate
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="XML Data Binding">
<Window.Resources>
<HierarchicalDataTemplate DataType="GameStats"
ItemsSource="{Binding XPath=*}">
<TextBlock FontStyle="Italic" Text="All Game Stats"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="GameStat" ItemsSource="{Binding XPath=*}">
<TextBlock FontWeight="Bold" FontSize="20" Text="{Binding XPath=@Type}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="HighScore">
<TextBlock Foreground="Blue" Text="{Binding XPath=.}"/>
</DataTemplate>
<XmlDataProvider x:Key="dataProvider" XPath="GameStats">
<x:XData>
<GameStats xmlns="">
<!-- -->
<GameStat Type="Beginner">
<HighScore>1203</HighScore>
</GameStat>
455
<GameStat Type="Intermediate">
<HighScore>1089</HighScore>
</GameStat>
<GameStat Type="Advanced">
<HighScore>541</HighScore>
</GameStat>
</GameStats>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<Grid>
<TreeView ItemsSource="{Binding Source={StaticResource dataProvider},
XPath=.}" />
</Grid>
</Window>
, HierarchicalDataTemplate
, DataTemp
late .
, HierarchicalDataTemplate
ItemsSource.
HierarchicalDataTemplates 13.3
ItemsSource XPath *,
XML-.
DataType
(
Window). XmlDataProvider
DataType XML. ,
,
ResourceDictionary. ,
DataType.
.13.13 XAML- 13.3.
, , TreeView Menu,
.
TreeView 13.3
TreeView Menu
.13.13. HierarchicalDataTemplate
TreeView
Menu ,
456
13.
XML- .
, RSS- Twitter :
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:georss="http://www.georss.org/georss">
...
</rss>
(, atom:link)
XPath, XmlNamespaceManager
XmlDataProvider Binding. :
<XmlDataProvider Source="http://twitter.com/statuses/user_timeline/24326956.rss"
XmlNamespaceManager="{StaticResource namespaceMapping}"
XPath="rss/channel" x:Key="dataProvider"/>
XmlNamespaceManager
, XmlNamespaceMapping
Collection, . :
<XmlNamespaceMappingCollection x:Key="namespaceMapping">
<XmlNamespaceMapping Uri="http://www.w3.org/2005/Atom" Prefix="atom"/>
<XmlNamespaceMapping Uri="http://www.georss.org/georss" Prefix="georss"/>
</XmlNamespaceMappingCollection>
,
XML, ,
. XPath,
:
"{Binding XPath=atom:link}"
XPath ,
. , XML-
, XmlNamespaceManager,
.
ObjectDataProvider
XmlDataProvider XML, ObjectDataProvider .NET.
! .
.NET . ObjectDataProvider?
,
. , :
-
457
,
, .
WPF :
Binding IsAsync, XmlDataProvider ObjectDataProvider
IsAsynchronous. ( , ?)
IsAsynchronous true, -
. IsAsynchronous false ObjectDataProvider,
true XmlDataProvider (
XML-, RSS-,
). , IsAsync (
false) true,
-.
Binding.IsAsync ,
- .
:
, ..
, WPF
IsAsync.
IsAsync
, , .
, Recompute,
( , )
. ,
PropertyChanged.
, .
XAML
, ,
, .
photos, . XAML-
ObjectDataProvider:
<Window.Resources>
<local:Photos x:Key="photos"/>
<ObjectDataProvider x:Key="dataProvider"
ObjectInstance="{StaticResource photos}"/>
</Window.Resources>
, : photos dataPro
vider. . Path Binding
, Binding ,
, ObjectDataProvider.
458
13.
ObjectDataProvider ,
( ),
:
<Window.Resources>
<!-- ObjectDataProvider : -->
<ObjectDataProvider x:Key="dataProvider" ObjectType="{x:Type local:Photos}"/>
</Window.Resources>
ObjectDataProvider ,
.
ConstructorParameters .
, Photos , Object
DataProvider :
<ObjectDataProvider x:Key="dataProvider" ObjectType="{x:Type local:Photos}">
<ObjectDataProvider.ConstructorParameters>
<sys:Int32>23</sys:Int32>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
x:Arguments
XAML2009, XAML2006 . ,
,
. ( , ,
, .) ,
XAML-,
, XAML.
, ObjectDataProvider ,
,
. ,
,
.
. ,
photos GetFolderName, ,
.
:
<ObjectDataProvider x:Key="dataProvider" ObjectType="{x:Type local:Photos}"
MethodName="GetFolderName"/>
,
MethodParameters ObjectDataProvider (
, ConstructorParameters). ,
ObjectDataProvider:
<TextBlock Text="{Binding Source={StaticResource dataProvider}}"/>
459
Path ,
.
ObjectDataProvider, ,
true BindsDirectlyToSource Binding
.
, DataSourceProvider ( Collection
ViewSource), ObjectDataProvider, XmlDataProvider
, .
,
.
,
, .
.
-, ,
. Binding
Mode,
, BindingMode:
OneWay .
TwoWay
.
OneWayToSource OneWay.
, .
OneTime , OneWay ,
.
.
TwoWay DataGrid
, TextBox, ,
.
OneWay,
, TextBox.Text, TwoWay. (
,
460
13.
, TwoWay .
,
.)
BindingMode, !
,
BindingMode , . ,
Label.Content, TextBox.Text Count
, BindingMode OneWay
( OneTime), Count , Two
Way OneWayToSource , - .
,
: Convert ConvertBack. (TwoWay)
, OneWayToSource ConvertBack.
FAQ
OneWayToSource?
, ,
.
, ,
,
. ,
,
.
OneWayToSource
, -
. -,
, -,
, OneWayToSource ,
, !
TwoWay OneWayToSource
, . ,
TextBox, TwoWay,
:
? Binding
UpdateSourceTrigger.
461
UpdateSourceTrigger ,
UpdateSourceTrigger:
PropertyChanged .
LostFocus , -
( , ).
Explicit Binding
Expression.UpdateSource. BindingExpression
, BindingOperations.GetBindingExp
ression GetBindingExpression ,
FrameworkElement FrameworkContentElement.
UpdateSourceTrigger
, Mode. , TextBox.Text
LostFocus.
, 3.
, GetMetadata
(, TextBox.TextProperty.GetMetadata()),
, BindsTwoWayByDefault DefaultUpdateSourceTrigger. ,
, ,
, .NET Reflector.
/
,
. , -
, .
, FrameworkElement FrameworkContentElement
SourceUpdated TargetUpdated, .
,
NotifyOnSourceUpdated ( NotifyOnTargetUpdated) Binding
true.
,
. - ,
,
462
13.
,
! ,
,
.
,
.
, ,
JPG- TextBox.
:
.jpg. TextBox ,
, ,
.
, -
. ,
, .
,
,
.
. -,
, -,
, , ,
.
. , ,
BindingMode OneWayToSource TwoWay.
Binding ValidationRules,
, ValidationRule.
- ,
. ,
, JpgValidation
Rule, ValidationRule,
Validate:
public class JpgValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string filename = value.ToString();
463
// :
if (!File.Exists(filename))
return new ValidationResult(false, "Value is not a valid file.");
// , .jpg:
if (!filename.EndsWith(".jpg", StringComparison.InvariantCultureIgnoreCase))
return new ValidationResult(false, "Value is not a .jpg file.");
// !
return new ValidationResult(true, null);
}
}
, , , false
ValidationResult; ,
true. ( ".jpg"
,
JPEG, .)
Binding:
<TextBox>
<TextBox.Text>
<Binding ...>
<Binding.ValidationRules>
<local:JpgValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
(
, TextBox ,
UpdateSourceTrigger LostFocus).
( ),
.
, ?
-
. .
Validation.ErrorTemplate,
-. (
.)
, , , ,
.
, , Validation.
HasError, -, true
Validation.Error ( ,
NotifyOnValidationError Binding true).
464
13.
, ,
.
, ,
JpgValidationRule, -
Validation.Errors. ,
.
, ( )
, .
-
, ,
ExceptionValidationRule. :
<TextBox>
<TextBox.Text>
<Binding ...>
<Binding.ValidationRules>
<ExceptionValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
ExceptionValidationRule ,
- .
,
, , .
,
System.ComponentModel.IDataErrorInfo
(
Windows Forms), DataError
ValidationRule .
TextBox :
<TextBox>
<TextBox.Text>
<Binding ...>
<Binding.ValidationRules>
<ExceptionValidationRule/>
<DataErrorValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
,
, ,
465
WPF ,
. WPF3.5 SP1 Binding
ValidatesOnExceptions ValidatesOnDataErrors,
ValidationRules
, . , XAML-
:
<TextBox>
<TextBox.Text>
<Binding ValidatesOnExceptions="True" ValidatesOnDataErrors="True" .../>
</TextBox.Text>
</TextBox>
,
, , UpdateSource
ExceptionFilter Binding. ,
- ,
Exception.
,
ValidationRule. UpdateSourceExceptionFilter
, , ,
ExceptionValidationRule.
, UpdateSourceException
Filter . Validation
Error,
ValidationError Validation.Errors , Validation.HasError true ,
, Validation.Error.
:
,
:
UpdateSourceExceptionFilter
.
ValidatesOnExceptions
ExceptionValidationRule, ErrorTemplate /
, Validation.Has
Error Validation.Error ( NotifyOnVa
lidationError true).
IDataErrorInfo,
ValidatesOnDataErrors
DataErrorValidationRule. ,
466
13.
,
.
Binding
, ,
DataGrid - ,
.
Binding
Group. Binding,
ValidationRule, Binding.
BindingGroup FrameworkElement (
FrameworkContentElement), BindingGroup ( ItemsCont
rol ItemBindingGroup,
, ItemsControl).
BindingGroup Binding,
DataContext, -.
BindingGroup Name,
Binding ;
BindingGroupName Name .
ValidationRule, Bind
ingGroup, Validate
BindingGroup. BindingGroup
, Items,
Binding , ValidationRule
,
. BindingGroup
( DataGrid),
IEditableObject.
WPF
. :
CompositeCollection
MultiBinding
PriorityBinding
CompositeCollection
CompositeCollection
/ .
,
, . XAML-
CompositeCollection, ,
photos, :
467
<CompositeCollection>
<CollectionContainer Collection="{Binding Source={StaticResource photos}}"/>
<local:Photo .../>
<local:Photo .../>
</CompositeCollection>
MultiBinding
MultiBinding Binding,
.
, WPF ,
. XAML ,
MultiBinding ,
ProgressBar, ,
, :
<ProgressBar ...>
<ProgressBar.Value>
<MultiBinding Converter="{StaticResource converter}">
<Binding Source="{StaticResource worker1}"/>
<Binding Source="{StaticResource worker2}"/>
<Binding Source="{StaticResource worker3}"/>
</MultiBinding>
</ProgressBar.Value>
</ProgressBar>
MultiBinding ,
Binding. IMultiValueConverter,
, .
:
public class ProgressConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, CultureInfo culture)
{
int totalProgress = 0;
// ,
// Worker
foreach (Worker worker in values)
totalProgress += worker.Progress;
return totalProgress;
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter, CultureInfo culture)
468
13.
{
return DependencyProperty.UnsetValue;
}
}
MultiBinding StringFormat.
{0} Binding, {1} ..
PriorityBinding
PriorityBinding MultiBinding ,
Binding. ,
!
(
),
, ,
.
. , Microsoft
Word
: 77257,
. 1/3 ( )
. 1/46. Photo Gallery
,
.
XAML- Priority
Binding:
<PriorityBinding>
<Binding Source="HighPri" Path="SlowSpeed" IsAsync="True"/>
<Binding Source="MediumPri" Path="MediumSpeed" IsAsync="True"/>
<Binding Source="LowPri" Path="FastSpeed"/>
</PriorityBinding>
Binding ,
(, , ),
(, , ).
.
: Twitter XAML
469
PriorityBinding Binding,
, IsAsync true,
.
(,
),
!
:
Twitter XAML
WPF
RSS-,
. 13.4
, RSS- Twitter.
Twitter, .13.14.
XAML- Kaxaml (http://ka
xaml.com), .
13.4. RSS-
( Twitter)
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="RSS Reader">
<Window.Resources>
<XmlDataProvider x:Key="Feed"
Source="http://twitter.com/statuses/user_timeline/24326956.rss"/>
</Window.Resources>
<DockPanel
DataContext="{Binding Source={StaticResource Feed},
XPath=/rss/channel/item}">
<TextBox DockPanel.Dock="Top" Text="{Binding Source={StaticResource Feed},
BindsDirectlyToSource=true, Path=Source,
UpdateSourceTrigger=PropertyChanged}"/>
<Label DockPanel.Dock="Top" Content="{Binding XPath=/rss/channel/title}"
FontSize="14" FontWeight="Bold"/>
<Label DockPanel.Dock="Top"
Content="{Binding XPath=/rss/channel/description}"/>
<ListBox DockPanel.Dock="Left" DisplayMemberPath="title"
ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" Width="300"/>
<Frame Source="{Binding XPath=link}"/>
</DockPanel>
</Window>
, RSS-
XmlDataProvider.
470
13.
:
Text TextBox
Source XmlDataProvider.
,
.
Source
, Binding TextBox BindsDirectlyToSource
true. Path RSS, .
TextBox Binding UpdateSourceTrigger
PropertyChanged,
. , Update
SourceTrigger=Explicit Go (),
.
, !
DisplayMemberPath ListBox
XPath, title ,
XML.
ListBox Frame /
.
Frame,
RSS- - TextBlock. HTML-
.
471
HTML,
Frame WebBrowser URL-
( link, ).
( )
.
,
. , ,
. ,
, ,
,
, .
-
, .
XmlDataProvider ,
, ,
XML- .
Binding
.
. WPF
,
. .
, Expression Blend,
( ),
. Blend
.
XAML-,
,
,
, .
14
14.
, ,
, WPF
, .
(CSS) HTML ,
, . HTML
, ,
SELECT (HTML-)?
, - ,
(, ).
,
WPF:
( CSS HTML).
, .
,
, WPF.
/ , .
,
.
, WPF
.
473
FAQ
WPF
?
!
WPF .
, (
BLINK HTML)?
, . WPF 2003,
, . , ,
, , .
WPF ,
,
. .
,
WPF-
Windows. Silverlight,
, Win
dows-. ,
WPF (
).
,
-,
,
Windows. (
), -, ,
.
Windows, .
,
.
, System.Windows.Style,
. ,
.
.
, , Button . 14.1.
.
,
, 14.1.
474
14. , ,
.14.1.
14.1. !
<StackPanel Orientation="Horizontal">
<Button FontSize="22" Background="Purple" Foreground="White"
Height="50" Width="50" RenderTransformOrigin=".5,.5">
<Button.RenderTransform>
<RotateTransform Angle="10"/>
</Button.RenderTransform>
1
</Button>
<Button FontSize="22" Background="Purple" Foreground="White"
Height="50" Width="50" RenderTransformOrigin=".5,.5">
<Button.RenderTransform>
<RotateTransform Angle="10"/>
</Button.RenderTransform>
2
</Button>
<Button FontSize="22" Background="Purple" Foreground="White"
Height="50" Width="50" RenderTransformOrigin=".5,.5">
<Button.RenderTransform>
<RotateTransform Angle="10"/>
</Button.RenderTransform>
3
</Button>
</StackPanel>
,
14.2. Style Setter,
. Setter
( ) .
, ,
,
.
. ,
buttonStyle ,
Resources Window - (
buttonStyle).
, , ,
. , ,
.
, .
475
14.2.
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<Style x:Key="buttonStyle">
<Setter Property="Button.FontSize" Value="22"/>
<Setter Property="Button.Background" Value="Purple"/>
<Setter Property="Button.Foreground" Value="White"/>
<Setter Property="Button.Height" Value="50"/>
<Setter Property="Button.Width" Value="50"/>
<Setter Property="Button.RenderTransformOrigin" Value=".5,.5"/>
<Setter Property="Button.RenderTransform">
<Setter.Value>
<RotateTransform Angle="10"/>
</Setter.Value>
</Setter>
</Style>
</StackPanel.Resources>
<Button Style="{StaticResource buttonStyle}" >1</Button>
<Button Style="{StaticResource buttonStyle}" >2</Button>
<Button Style="{StaticResource buttonStyle}" >3</Button>
</StackPanel>
! , Style
buttonStyle,
14.2. BasedOn, ,
:
<Style x:Key="buttonStyleWithBold" BasedOn="{StaticResource buttonStyle}">
<!-- , buttonStyle, -->
<Setter Property="Button.FontWeight" Value="Bold"/>
</Style>
Style
XAML- ( ),
, ,
14.2. Style ,
.
Style 14.2 ,
. 14.3
476
14. , ,
.14.2.
14.3.
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<Style x:Key="controlStyle">
<Setter Property="Control.FontSize" Value="22"/>
<Setter Property="Control.Background" Value="Purple"/>
<Setter Property="Control.Foreground" Value="White"/>
<Setter Property="Control.Height" Value="50"/>
<Setter Property="Control.Width" Value="50"/>
<Setter Property="Control.RenderTransformOrigin" Value=".5,.5"/>
<Setter Property="Control.RenderTransform">
<Setter.Value>
<RotateTransform Angle="10"/>
</Setter.Value>
</Setter>
</Style>
</StackPanel.Resources>
<Button Style="{StaticResource controlStyle}">1</Button>
<ComboBox Style="{StaticResource controlStyle}">
<ComboBox.Items>2</ComboBox.Items>
</ComboBox>
<Expander Style="{StaticResource controlStyle}" Content="3"/>
<TabControl Style="{StaticResource controlStyle}">
<TabControl.Items>4</TabControl.Items>
</TabControl>
<ToolBar Style="{StaticResource controlStyle}">
<ToolBar.Items>5</ToolBar.Items>
</ToolBar>
<InkCanvas Style="{StaticResource controlStyle}"/>
<TextBox Style="{StaticResource controlStyle}" Text="7"/>
</StackPanel>
, ,
- , ;
. , InkCanvas Foreground
FontSize. ,
14.3, InkCanvas (Background, Height, Width
..) .
477
( ) Setter
, , , -
Setter 14.3 InkCanvas,
Control, InkCanvas Control!
(
, .NET).
InkCanvas
( DependencyProperty.Register), , Backg
round, (
DependencyProperty.AddOwner).
, ,
Setter.Property, ,
. ,
, .
.
, 14.3 Setter ,
14.2. Button.XXX, Control.
XXX, . ,
14.3 TextBlock, , Button.Fore
ground TextBlock, Button.Background
TextBlock! , TextBlock
Control Foreground,
Background. (Control Background
, Panel InkCanvas, TextBlock
, TextElement, FlowDocument .)
.
, ,
. , 14.3
, controlStyle,
, :
<Button Style="{StaticResource controlStyle}" Background="Red">1</Button>
, 3 WPF.
, .
478
14. , ,
, Style Resources.
,
, ,
- .
, -
, TargetType. ,
Button (
Button):
<Style x:Key="buttonStyle" TargetType="{x:Type Button}">
<Setter Property="Button.FontSize" Value="22"/>
<Setter Property="Button.Background" Value="Purple"/>
<Setter Property="Button.Foreground" Value="White"/>
<Setter Property="Button.Height" Value="50"/>
<Setter Property="Button.Width" Value="50"/>
<Setter Property="Button.RenderTransformOrigin" Value=".5,.5"/>
<Setter Property="Button.RenderTransform">
<Setter.Value>
<RotateTransform Angle="10"/>
</Setter.Value>
</Setter>
</Style>
, Button,
. , 14.3
TargetType="{x:Type Control}",
, InkCanvas.
, TargetType,
Setter. , XAML-
:
<Style x:Key="buttonStyle" TargetType="{x:Type Button}">
<Setter Property="FontSize" Value="22"/>
<Setter Property="Background" Value="Purple"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Width" Value="50"/>
<Setter Property="RenderTransformOrigin" Value=".5,.5"/>
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="10"/>
</Setter.Value>
479
</Setter>
</Style>
TargetType .
Key,
.
, ,
.
Style.
, Window.Resources,
Window. ,
, ,
.
<Application ...>
<Application.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="FontSize" Value="22"/>
<Setter Property="Background" Value="Purple"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Width" Value="50"/>
<Setter Property="RenderTransformOrigin" Value=".5,.5"/>
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="10"/>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
x:Key !
.
,
- . ,
, Style null.
?
, , ResourceDictionary,
. .
TargetType (
Type, ). , Target
Type Button, :
480
14. , ,
TargetType ResourceDictionary
,
.
Style ,
:
[DictionaryKeyProperty("TargetType")]
DictionaryKeyPropertyAttribute
, ,
.
,
TargetType!
,
TargetType,
, TargetType. ,
. ,
ToggleButton , ,
CheckBox (, CheckBox ToggleButton).
(
, ). ,
,
.
. ,
, FrameworkElement FrameworkContentElement,
FocusVisualStyle Style. , Focus
VisualStyle, , ; ,
, ( ,
).
. , ItemsControl ItemContainer
Style, (, ListBoxItem
ComboBoxItem). , ToolBar,
ResourceKey, ,
ButtonStyleKey TextBoxStyleKey. XXXStyleKey
,
. :
481
<Application ...>
<Application.Resources>
<Style x:Key="{x:Static ToolBar.ButtonStyleKey}" TargetType="{x:Type Button}">
...
</Style>
</Application.Resources>
</Application>
, ToolBar ResourceKey,
Style, ,
.
ItemsControl , ItemCon
tainerStyle null,
. ToolBar
, .
, 3,
Setter , (/ Trigger
Action).
, .
, :
.
.NET.
.
FrameworkElement, Style, DataTemplate ControlTemplate (
) Triggers,
, Framework
Element . , Style
,
,
.
. 17 .
( Trigger)
Setter,
. ,
Setter.
482
14. , ,
, buttonStyle
, ;
, Foreground Black White:
<Style x:Key="buttonStyle" TargetType="{x:Type Button}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="10"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Black"/>
</Trigger>
</Style.Triggers>
<Setter Property="FontSize" Value="22"/>
<Setter Property="Background" Value="Purple"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Width" Value="50"/>
<Setter Property="RenderTransformOrigin" Value=".5,.5"/>
</Style>
.14.3 .
Foreground Black,
, Windows 7
.
Button, ,
Button (. ).
, Background .
IsMouseOver=false
IsMouseOver=true
.14.3.
.
JpgValidationRule Text
Box, JPG-.
, ,
, Validation.
HasError:
<Style x:Key="textBoxStyle" TargetType="{x:Type TextBox}">
<Style.Triggers>
483
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="Red"/>
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
,
ToolTip. ,
RelativeSource Validation.Errors
, .
TextBox, ,
, .14.4:
<TextBox Style="{StaticResource textBoxStyle}">
<TextBox.Text>
<Binding ...>
<Binding.ValidationRules>
<local:JpgValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
.14.4.
14.4
AlternationIndex ItemsControl,
10 .
ItemContainerStyle ItemsCont
rol , . (
, , , ListBox
ListBoxItem.) .14.5 .
14.4. ,
, ListBoxItem TreeViewItem
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Orientation="Horizontal">
<StackPanel.Resources>
<Style x:Key="AlternatingRowStyle" TargetType="{x:Type Control}">
<Setter Property="Background" Value="Green"/>
484
14. , ,
,
AlternationIndex 1,
485
, . ,
, AlternationCount 2 (
0, 1, 0, 1, ).
, ListBoxItem,
TreeViewItem, Control ( ,
),
ItemsControl.AlternationIndex, - (,
ListBox.AlternationIndex). , . 14.5,
TreeViewItem, , Alternation
Count 2, ItemContainerStyle
. , TreeViewItem (
) .
,
.NET, . (,
Setter -
.)
,
Triggers DataTrigger /.
.NET
Binding, .
TextBox ,
IsEnabled Text,
. Text "disabled", IsEnabled
false (,
):
<StackPanel Width="200">
<StackPanel.Resources>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}"
Value="disabled">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
<Setter Property="Background"
Value="{Binding RelativeSource={RelativeSource Self}, Path=Text}"/>
</Style>
</StackPanel.Resources>
<TextBox Margin="3"/>
</StackPanel>
Binding Text ;
Background TextBox
486
14. , ,
( Brush).
, ,
. (
Setter
, , .)
.14.6 Text.
.14.6. TextBox ,
"disabled"
:
=, .
:
(
).
(
).
. Style.Triggers
,
Setter
:
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="10"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Black"/>
</Trigger>
<Trigger Property="IsFocused" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="10"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Black"/>
487
</Trigger>
</Style.Triggers>
Setter, .
Setter .
. ,
Trigger MultiTrigger
DataTrigger MultiDataTrigger. MultiTrig
ger, MultiDataTrigger Conditions,
, Trigger DataTrigger.
, MultiTrigger :
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True"/>
<Condition Property="IsFocused" Value="True"/>
</MultiTrigger.Conditions>
<Setter Property="RenderTransform">
<Setter.Value>
<RotateTransform Angle="10"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Black"/>
</MultiTrigger>
</Style.Triggers>
, EventSetter (
, Setter),
, . EventSetter
, Setter:
488
14. , ,
, Control, ,
. Button
Background Foreground (
), TabControl -
TabStripPlacement ..
.
,
, ,
. , ( WPF)
;
WPF (
Windows).
( ).
, WPF
. ,
Expander .14.2,
.
Expander. Expander ArrowBrush ArrowColor,
Expander !
. ,
,
. ControlTemplate,
FrameworkTemplate. , FrameworkTemplate,
: DataTemplate ( ) ItemsPanelTemplate
(10).
.NET, ,
TextBlock,
, ToString. ItemsPanelTemplate
ItemsPanel , ItemsControl;
.
489
(!) ,
, .
.
ControlTemplate Visual
Tree, ,
. ControlTemplate ( , XAML),
Control Page, Temp
late. 14.5 ,
, Button.
.14.7 .
14.5. ControlTemplate
<Grid>
<Grid.Resources>
<ControlTemplate x:Key="buttonTemplate">
<Grid>
<Ellipse Width="100" Height="100">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="Blue"/>
<GradientStop Offset="1" Color="Red"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Ellipse Width="80" Height="80">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="White"/>
<GradientStop Offset="1" Color="Transparent"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
</Grid>
</ControlTemplate>
</Grid.Resources>
<Button Template="{StaticResource buttonTemplate}">OK</Button>
</Grid>
, (
Ellipse), Grid
. , -
Click, IsDefault
. - Button!
490
14. , ,
.14.7. , ControlTemplate
14.5 Button -
. FrameworkElement Frame
workContentElement TemplatedParent
.
,
Triggers. 14.6 ControlTemplate
. Button.IsMouseOver
, Button.IsPressed ,
ScaleTransform, .
.14.8.
14.6. ControlTemplate,
<Grid>
<Grid.Resources>
<ControlTemplate x:Key="buttonTemplate">
<Grid>
<Ellipse x:Name="outerCircle" Width="100" Height="100">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="Blue"/>
<GradientStop Offset="1" Color="Red"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Ellipse Width="80" Height="80">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="White"/>
<GradientStop Offset="1" Color="Transparent"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
491
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="Button.IsMouseOver" Value="True">
<Setter TargetName="outerCircle" Property="Fill" Value="Orange"/>
</Trigger>
<Trigger Property="Button.IsPressed" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform ScaleX=".9" ScaleY=".9"/>
</Setter.Value>
</Setter>
<Setter Property="RenderTransformOrigin" Value=".5,.5"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Grid.Resources>
<Button Template="{StaticResource buttonTemplate}">OK</Button>
</Grid>
IsMouseOver=True
IsPressed=True
( IsMouseOver=True)
.14.8. ,
ControlTemplate 14.6
,
outerCircle. ,
. TargetName Set
ter ( ),
Fill Orange outerCircle.
TargetName, ,
, Button
Fill .
.
. Scale
Transform ( RenderTransform) ,
RenderTransformOrigin, .
.14.8 , ,
( 10%)
.
492
14. , ,
x:Name
, .
x:Name . ,
.
,
( , XAML).
-
, FindName Template ,
.
Style, ControlTemplate TargetType,
. ,
(, Trigger.Property Setter.Pro
perty). , 14.6
:
<ControlTemplate x:Key="buttonTemplate" TargetType="{x:Type Button}">
<Grid>
...
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="outerCircle" Property="Fill" Value="Orange"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform ScaleX=".9" ScaleY=".9"/>
</Setter.Value>
</Setter>
<Setter Property="RenderTransformOrigin" Value=".5,.5"/>
</Trigger>
493
</ControlTemplate.Triggers>
</ControlTemplate>
, Proper
ty Setter .
, TargetName,
Control. (
TargetType Control.)
Style, TargetType
x:Key ( ).
,
; ,
.
-
, , .
, , ,
. ,
"OK",
. ,
, ,
.
Content ContentControl
. , TemplateBindingEx
tension .
,
Binding, ,
. TemplateBinding, Exten
sion XAML .
TemplateBinding ,
,
Property TemplateBinding. , 14.6
TextBlock,
Content Button:
<TextBlock Text="{TemplateBinding Property=Button.Content}"/>
, TemplateBinding ,
, :
<TextBlock Text="{TemplateBinding Button.Content}"/>
TargetType (
, ContentControl),
:
494
14. , ,
, ,
TextBlock
.
Content , TextBlock
ContentControl. 14.7 . ContentControl
Margin, Viewbox,
.
14.7. ControlTemplate,
<ControlTemplate x:Key="buttonTemplate" TargetType="{x:Type Button}">
<Grid>
<Ellipse x:Name="outerCircle" Width="100" Height="100">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="Blue"/>
<GradientStop Offset="1" Color="Red"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Ellipse Width="80" Height="80">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="White"/>
<GradientStop Offset="1" Color="Transparent"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Viewbox>
<ContentControl Margin="20" Content="{TemplateBinding Content}"/>
</Viewbox>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="outerCircle" Property="Fill" Value="Orange"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform ScaleX=".9" ScaleY=".9"/>
</Setter.Value>
</Setter>
<Setter Property="RenderTransformOrigin" Value=".5,.5"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
.14.9 ,
. "OK",
495
Image.
.
.14.9. , 14.7
ContentControl,
ContentPresenter.
, ContentControl,
. ContentPresenter
, ContentControl
(, , ContentPresenter)!
14.7
<ContentControl Margin="20" Content="{TemplateBinding Content}"/>
:
<ContentPresenter Margin="20" Content="{TemplateBinding Content}"/>
ContentPresenter :
Content {TemplateBinding Content},
. :
<ContentPresenter Margin="20"/>
, TargetType
, ContentControl (, Button).
ContentPresenter
ContentControl, .
TemplateBinding
,
Freezable!
TemplateBinding
VisualTree, .
, TemplateBinding ,
Freezable. ,
Color Brush .
496
14. , ,
TemplateBinding ,
Binding. ,
Binding, RelativeSource {Relati
veSource TemplatedParent}, Path ,
. Binding ,
TemplateBinding .
,
, ,
: Height Width,
, Background, Padding .. (, Foreground, Font
Size, FontWeight )
,
.
14.8 14.7,
Background, Padding Content Button.
,
Height Width,
. 14.8 ContentPresenter ContentControl,
.
14.8. ControlTemplate,
<ControlTemplate x:Key="buttonTemplate" TargetType="{x:Type Button}">
<Grid>
<Ellipse x:Name="outerCircle">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0"
Color="{Binding RelativeSource={RelativeSource TemplatedParent},
Path=Background.Color}"/>
<GradientStop Offset="1" Color="Red"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Ellipse RenderTransformOrigin=".5,.5">
<Ellipse.RenderTransform>
<ScaleTransform ScaleX=".8" ScaleY=".8"/>
</Ellipse.RenderTransform>
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="White"/>
<GradientStop Offset="1" Color="Transparent"/>
</LinearGradientBrush>
497
</Ellipse.Fill>
</Ellipse>
<Viewbox>
<ContentPresenter Margin="{TemplateBinding Padding}"/>
</Viewbox>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="outerCircle" Property="Fill" Value="Orange"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform ScaleX=".9" ScaleY=".9"/>
</Setter.Value>
</Setter>
<Setter Property="RenderTransformOrigin" Value=".5,.5"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
Padding Margin
ContentPresenter. Padding
Margin
. , , , !
,
,
Background. {TemplateBinding Backgro
und} Fill outerCircle,
, .. , ,
,
. ,
Background.
GradientStop.Color {Template
Binding Background}, Color, Background
Brush ( GradientStop Freezable)!
Binding,
Color. (, Binding ,
Background SolidColorBrush,
Color .)
( Grid)
Height Width,
.
ActualHeight ActualWidth. ,
-
! ,
, Width Height.
498
14. , ,
,
Viewbox.
, 14.8,
ScaleTransform , 80%
.
,
. , ScaleTransform
. ( ,
,
Margin.)
.14.10
:
<StackPanel Orientation="Horizontal">
<Button Template="{StaticResource buttonTemplate}"
Height="100" Width="100" FontSize="80" Background="Black"
Padding="20" Margin="5">1</Button>
<Button Template="{StaticResource buttonTemplate}"
Height="150" Width="250" FontSize="80" Background="Yellow"
Padding="20" Margin="5">2</Button>
<Button Template="{StaticResource buttonTemplate}"
Height="200" Width="200" FontSize="80" Background="White"
Padding="20" Margin="5">3</Button>
</StackPanel>
.14.10. ,
14.8
499
TemplateBinding
Binding, TemplateBinding
. TemplateBinding Converter Converter
Parameter, , , ConverterCulture.
, Binding.
, , .
, 14.8 ,
.
? Button !
,
20 .
, Button,
HoverBrush. -
.
, . ,
.
- ,
- .
. ,
,
. ,
, Control, Brush: Back
ground, Foreground BorderBrush. Background Foreground
14.8,
, . ( ,
.)
BorderBrush . ,
?
,
, . ,
IsMouseOver 14.8,
BorderBrush:
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="outerCircle" Property="Fill"
Value="{Binding RelativeSource={RelativeSource TemplatedParent},
Path=BorderBrush}"/>
</Trigger>
500
14. , ,
Binding, TemplateBinding,
Trigger .
,
, -
! , ,
, ,
(,
).
,
. WPF
! , -
.
, . ,
, 14.8, CheckBox Toggle
Button ( TargetType).
Checked,
Unchecked Indeterminate,
!
14.8 Button!
, , IsEnabled
false, IsDefaulted true,
.
, -
,
.
.
, ProgressBar
, . 14.9
ProgressBar ( ),
.
Value -,
.
, IsEnabled IsIndeterminate
. .14.11 14.12
, :
<ProgressBar Foreground="{StaticResource foregroundBrush}" Width="100"
Height="100" Value="10" Template="{StaticResource progressPie}"/>
501
0%
10%
50%
75%
100%
.14.11. ProgressBar
IsEnabled=false
IsIndeterminate=true
.14.12. ProgressBar
foregroundBrush :
<LinearGradientBrush x:Key="foregroundBrush" StartPoint="0,0" EndPoint="1,1">
<GradientStop Offset="0" Color="LightGreen"/>
<GradientStop Offset="1" Color="DarkGreen"/>
</LinearGradientBrush>
14.9. ProgressBar
<Application x:Class="WindowsApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WindowsApplication1"
StartupUri="Window1.xaml">
<Application.Resources>
<ControlTemplate x:Key="progressPie" TargetType="{x:Type ProgressBar}">
<!-- -->
<ControlTemplate.Resources>
<local:ValueMinMaxToPointConverter x:Key="converter1"/>
<local:ValueMinMaxToIsLargeArcConverter x:Key="converter2"/>
</ControlTemplate.Resources>
<!-- -->
<Viewbox>
<Grid Width="20" Height="20">
<Ellipse x:Name="background" Stroke="{TemplateBinding BorderBrush}"
StrokeThickness="{TemplateBinding BorderThickness}"
Width="20" Height="20" Fill="{TemplateBinding Background}"/>
<Path x:Name="pie" Fill="{TemplateBinding Foreground}">
<Path.Data>
<PathGeometry>
<PathFigure StartPoint="10,10" IsClosed="True">
502
14. , ,
<LineSegment Point="10,0"/>
<ArcSegment Size="10,10" SweepDirection="Clockwise">
<ArcSegment.Point>
<MultiBinding Converter="{StaticResource converter1}">
<Binding RelativeSource="{RelativeSource TemplatedParent}"
Path="Value"/>
<Binding RelativeSource="{RelativeSource TemplatedParent}"
Path="Minimum"/>
<Binding RelativeSource="{RelativeSource TemplatedParent}"
Path="Maximum"/>
</MultiBinding>
</ArcSegment.Point>
<ArcSegment.IsLargeArc>
<MultiBinding Converter="{StaticResource converter2}">
<Binding RelativeSource="{RelativeSource TemplatedParent}"
Path="Value"/>
<Binding RelativeSource="{RelativeSource TemplatedParent}"
Path="Minimum"/>
<Binding RelativeSource="{RelativeSource TemplatedParent}"
Path="Maximum"/>
</MultiBinding>
</ArcSegment.IsLargeArc>
</ArcSegment>
</PathFigure>
</PathGeometry>
</Path.Data>
</Path>
</Grid>
</Viewbox>
<!-- -->
<ControlTemplate.Triggers>
<Trigger Property="IsIndeterminate" Value="True">
<Setter TargetName="pie" Property="Visibility" Value="Hidden"/>
<Setter TargetName="background" Property="Fill">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Offset="0" Color="Yellow"/>
<GradientStop Offset="1" Color="Brown"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="pie" Property="Fill">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Offset="0" Color="Gray"/>
<GradientStop Offset="1" Color="White"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
503
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Application.Resources>
</Application>
Viewbox, Grid
2020 .
Background, BorderBrush BorderThickness ,
( 10), . Path (
), - Foreground
MultiBinding ( ,
14.10). MultiBinding, TemplateBinding
Binding,
ProgressBar: Value, Minimum Maximum. ,
.14.12,
Brush ( IsIndeterminate ). ,
IsIndeterminate
, , ,
. ,
ProgressBar. , Orientation ,
, , ,
.
: 14.9 ,
Resources ControlTemplate. Style,
, FrameworkTemplate,
Resources. ,
.
14.10. , 14.9
public class ValueMinMaxToIsLargeArcConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, CultureInfo culture)
{
double value = (double)values[0];
double minimum = (double)values[1];
double maximum = (double)values[2];
// true, value 50%
return ((value * 2) >= (maximum - minimum));
504
14. , ,
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
public class ValueMinMaxToPointConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, CultureInfo culture)
{
double value = (double)values[0];
double minimum = (double)values[1];
double maximum = (double)values[2];
// value 0 360
double current = (value / (maximum - minimum)) * 360;
// ,
// ArcSegment
if (current == 360)
current = 359.999;
// 90 , 0
current = current - 90;
//
current = current * 0.017453292519943295;
//
double x = 10 + 10 * Math.Cos(current);
double y = 10 + 10 * Math.Sin(current);
return new Point(x, y);
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
.
IsLargeArc ArcSegment (. 14.9) true,
, false .
, ValueMinMaxToIsLargeArcConverter
ProgressBar
.
505
. Point
, .
Value (),
.
, 10,
(10,10).
,
.
, ,
. ,
WPF4
(Visual State Manager VSM),
Silverlight.
VSM ,
,
. , VSM
. , Expres
sion Blend .
WPF . ,
. .
ProgressBar PART_Indi
cator PART_Track, , Width (
Height ) PART_Indicator
( )
PART_Track, Value, Minimum
Maximum .
(. 14.9) , , .
, ProgressBar,
(
).
ComboBox Popup
PART_Popup,
DropDownClosed ComboBox.
TextBox PART_EditableTextBox,
ComboBox
, .
506
14. , ,
, Text
Calendar
PART_CalendarItem
PART_Root
CalendarItem
Panel
CalendarItem
DayTitleTemplate
PART_DisabledVisual
PART_HeaderButton
PART_MonthView
PART_NextButton
PART_PreviousButton
PART_Root
PART_YearView
DataTemplate
FrameworkElement
Button
Grid
Button
Button
FrameworkElement
Grid
ComboBox
PART_EditableTextBox
PART_Popup
TextBox
Popup
DataGridColumnFloatingHeader
PART_VisualBrushCanvas
Canvas
DataGridColumnHeader
PART_LeftHeaderGripper
PART_RightHeaderGripper
Thumb
Thumb
DataGridColumnHeadersPresenter
PART_FillerColumnHeader
DataGridColumnHeader
DataGridRowHeader
PART_BottomHeaderGripper
PART_TopHeaderGripper
Thumb
Thumb
DatePicker
PART_Button
PART_Popup
PART_Root
PART_TextBox
Button
Popup
Grid
DatePickerTextBox
DatePickerTextBox
PART_Watermark
ContentControl
DocumentViewer
PART_ContentHost
PART_FindToolBarHost
ScrollViewer
ContentControl
507
DocumentViewerBase
PART_FindToolBarHost
Decorator
FlowDocumentReader
PART_ContentHost
PART_FindToolBarHost
Decorator
Decorator
FlowDocumentScrollViewer
PART_ContentHost
PART_FindToolBarHost
PART_ToolBarHost
ScrollViewer
Decorator
Decorator
Frame
PART_FrameCP
ContentPresenter
GridViewColumnHeader
PART_FloatingHeaderCanvas
PART_HeaderGripper
Canvas
Thumb
MenuItem
PART_Popup
Popup
NavigationWindow
PART_NavWinCP
ContentPresenter
ProgressBar
PART_GlowRect
PART_Indicator
PART_Track
FrameworkElement
FrameworkElement
FrameworkElement
ScrollBar
PART_Track
Track
ScrollViewer
PART_HorizontalScrollBar
PART_ScrollContentPresenter
PART_VerticalScrollBar
ScrollBar
ScrollContentPresenter
ScrollBar
Slider
PART_SelectionRange
PART_Track
FrameworkElement
Track
StickyNoteControl
PART_ClipboardSeparator
Separator
PART_CloseButton
PART_ContentControl
PART_CopyMenuItem
PART_EraseMenuItem
PART_IconButton
PART_InkMenuItem
PART_PasteMenuItem
PART_ResizeBottomRightThumb
PART_SelectMenuItem
PART_TitleThumb
Button
ContentControl
MenuItem
MenuItem
Button
MenuItem
MenuItem
Thumb
MenuItem
Thumb
TabControl
PART_SelectedContentHost
ContentPresenter
TextBoxBase
PART_ContentHost
FrameworkElement
ToolBar
PART_ToolBarOverflowPanel
PART_ToolBarPanel
ToolBarOverflowPanel
ToolBarPanel
TreeViewItem
PART_Header
FrameworkElement
508
14. , ,
, , WPF
( ),
(
), !
, , .
, , -
,
ProgressBar.
, Templa
tePartAttribute, , .
. WPF
, PART_XXX (,
, CalendarItem); Silverlight
.
, ,
. , , ,
,
!
,
WPF4. ,
(
VisualStateManager.GoToState).
, .
, WPF4
.
Expression Blend,
Silverlight.
, ,
. , Button
CommonStates: Normal, MouseOver, Pressed Disabled,
FocusStates: Unfocused Focused.
Button ,
Normal Unfocused.
, ,
(, NormalUnfocused, NormalFocused, MouseOver
Unfocused, MouseOverFocused .).
.14.2 ,
WPF.
DataGridRow DataGridRowHeader;
. (, -
.) , , ;
509
ButtonBase
CommonStates
FocusStates
Unfocused, Focused
SelectionStates
Unselected, Selected
CalendarButtonFocus
States
CalendarButtonUnfocused, CalendarBut
tonFocused
ActiveStates
Inactive, Active
SelectionStates
Unselected, Selected
CalendarButtonFocus
States
CalendarButtonUnfocused, Calendar
ButtonFocused
ActiveStates
Inactive, Active
DayStates
RegularDay, Today
BlackoutDayStates
NormalDay, BlackoutDay
CalendarItem
CommonStates
Normal, Disabled
ComboBox
CommonStates
FocusStates
EditStates
Editable, Uneditable
CommonStates
Normal, MouseOver
SelectionStates
FocusStates
Unfocused, Focused
Control
ValidationStates
DataGrid
CommonStates
Normal, Disabled
DataGridCell
CommonStates
Normal, MouseOver
SelectionStates
Unselected, Selected
FocusStates
Unfocused, Focused
CurrentStates
Regular, Current
InteractionStates
Display, Editing
CalendarButton
CalendarDayButton
ComboBoxItem
510
14. , ,
14.2 ()
DataGridColumnHeader
SortStates
DataGridRow
CommonStates
DataGridRowHeader
CommonStates
DatePicker
CommonStates
Normal, Disabled
DatePickerTextBox
WatermarkStates
Unwatermarked, Watermarked
Expander
CommonStates
FocusStates
Unfocused, Focused
ExpansionStates
Expanded, Collapsed
CommonStates
ListBoxItem
CommonStates
SelectionStates
FocusStates
Unfocused, Focused
ProgressBar
CommonStates
Determinate, Indeterminate
RangeBase
CommonStates
FocusStates
Unfocused, Focused
CommonStates
FocusStates
Unfocused, Focused
TabControl
CommonStates
Normal, Disabled
TabItem
CommonStates
SelectionStates
Unselected, Selected
FocusStates
Unfocused, Focused
ScrollBar
511
TextBox
CommonStates
ReadOnly ( TextBoxBase)
TextBoxBase
CommonStates
FocusStates
Unfocused, Focused
CommonStates
FocusStates
Unfocused, Focused
ToggleButton
CheckStates
ToolTip
OpenStates
Open, Closed
FocusStates
Unfocused, Focused
CommonStates
SelectionStates
FocusStates
Unfocused, Focused
ExpansionStates
Collapsed, Expanded
HasItemsStates
HasItems, NoItems
Thumb
TreeViewItem
, ,
VisualStateManager.VisualStateGroups
VisualSta
teGroup,
VisualState.
14.11
14.9, ProgressBar ;
.
ProgressBar Determinate Indeterminate,
Normal Disabled, -
, IsEnabled
false. , , IsIn
determinate true,
Indeterminate.
14.11.
VSM
<Application x:Class="WindowsApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WindowsApplication1"
StartupUri="Window1.xaml">
<Application.Resources>
<ControlTemplate x:Key="progressPie" TargetType="{x:Type ProgressBar}">
512
14. , ,
<!-- -->
<ControlTemplate.Resources>
<local:ValueMinMaxToPointConverter x:Key="converter1"/>
<local:ValueMinMaxToIsLargeArcConverter x:Key="converter2"/>
</ControlTemplate.Resources>
<!-- -->
<Viewbox>
<!-- -->
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Determinate"/> <!-- -->
<VisualState Name="Indeterminate">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="pie"
Storyboard.TargetProperty="Opacity" To="0" Duration="0"/>
<DoubleAnimation Storyboard.TargetName="backgroundNormal"
Storyboard.TargetProperty="Opacity" To="0" Duration="0"/>
<DoubleAnimation Storyboard.TargetName="backgroundIndeterminate"
Storyboard.TargetProperty="Opacity" To="1" Duration="0"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid Width="20" Height="20">
<Ellipse x:Name="backgroundIndeterminate" Opacity="0"
Stroke="{TemplateBinding BorderBrush}"
StrokeThickness="{TemplateBinding BorderThickness}"
Width="20" Height="20">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Offset="0" Color="Yellow"/>
<GradientStop Offset="1" Color="Brown"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<Ellipse x:Name="backgroundNormal" Stroke="{TemplateBinding BorderBrush}"
StrokeThickness="{TemplateBinding BorderThickness}"
Width="20" Height="20" Fill="{TemplateBinding Background}"/>
<Path x:Name="pie" Fill="{TemplateBinding Foreground}">
<Path.Data>
<PathGeometry>
<PathFigure StartPoint="10,10" IsClosed="True">
<LineSegment Point="10,0"/>
<ArcSegment Size="10,10" SweepDirection="Clockwise">
<ArcSegment.Point>
<MultiBinding Converter="{StaticResource converter1}">
<Binding RelativeSource="{RelativeSource TemplatedParent}"
Path="Value"/>
<Binding RelativeSource="{RelativeSource TemplatedParent}"
Path="Minimum"/>
513
VisualState Storyboard,
17.
( 14.11),
. Storyboard
Fill , , LinearGradientBrush,
backgroundNormal,
, backgroundIndeterminate,
( Opacity 0).
Indeterminate
,
Opacity backgroundNormal 0,
514
14. , ,
backgroundIndeterminate 1.
, Duration
DoubleAnimation. 17
.
Button (. 14.8) ,
VSM.
,
TemplateVisualStateAttri
bute. WPF
.
VisualStateGroup Transitions ,
VisualTransition,
.
. 17.
, Template Control
Style,
:
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
...
</ControlTemplate>
</Setter.Value>
</Setter>
...
</Style>
, :
. ,
,
- !
,
,
515
. ,
, -,
.
.
, ProgressBar
. ,
. ,
Foreground - ( 14.9),
ProgressBar
Foreground. Foreground Progress
Bar , !
, Setter Style,
,
ProgressBar
Foreground. {TemplateBinding Foreground}
. Style :
<Style x:Key="pieStyle" TargetType="{x:Type ProgressBar}">
<Setter Property="Foreground">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Offset="0" Color="LightGreen"/>
<GradientStop Offset="1" Color="DarkGreen"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ProgressBar}">
...
<Path x:Name="pie" Fill="{TemplateBinding Foreground}">
...
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
:
<!-- -->
<ProgressBar Style="{StaticResource pieStyle}"
Width="100" Height="100" Value="10"/>
<!-- -->
<ProgressBar Style="{StaticResource pieStyle}" Foreground="Red"
Width="100" Height="100" Value="10"/>
, ,
Width Height.
516
14. , ,
Style ,
: Style, ,
Style, Setter Style!
,
.
Setter .
FAQ
, ?
( BasedOn
Style) . XAML-
,
. ,
, ,
,
WPF , .
XAML-
, ( ,
, ):
string xaml = XamlWriter.Save(someControl.Template);
,
. ,
DefaultStyleKey (
), Style:
//
object defaultStyleKey = someElement.GetValue(
FrameworkElement.DefaultStyleKeyProperty);
//
Style style = (Style)Application.Current.FindResource(defaultStyleKey);
// XAML-
string xaml = System.Windows.Markup.XamlWriter.Save(style);
FindResource
, typeof(Button) Button (
).
, :
Windows SDK, XAML-
, WPF.
517
, , Presentation
Framework.Aero.dll.
Expression Blend,
Edit TemplateEdit a Copy (
), XAML-.
(XAML- , WPF,
Blend Program Files.)
. Blend
, .
.
()
, . WPF
, .
,
WPF (. 12
) .
. Win32 Windows Forms,
, , WPF-
XAML, , ,
. ( XAML- ;
, , -
. . FAQ .)
XAML-?
Window Page XAML-,
( , 2 XAML).
, .
XAML- ,
, ..
( , ,
.) Visual Studio 2010
, XAML.
Page,
. ,
Page .
518
14. , ,
, Resource
Dictionary. ,
- ,
. ,
ResourceDictionary / .
,
Window ,
(.14.13):
<Window x:Class="WindowsApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Please Wait" Height="200" Width="300" ResizeMode="NoResize">
<Grid>
<StackPanel Style="{DynamicResource DialogStyle}">
<Label Style="{DynamicResource HeadingStyle}">Loading...</Label>
<ProgressBar Value="35" MinHeight="20" Margin="20"/>
<Button Style="{DynamicResource CancelButtonStyle}" Width="70"
Click="Cancel_Click">Cancel</Button>
</StackPanel>
</Grid>
</Window>
.14.13. ,
,
Style. ,
,
. , , Cancel
() .
Cancel CancelButtonStyle.
,
.
Window ,
.14.13, App.xaml,
Style, :
519
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
<Application.Resources>
<Style x:Key="DialogStyle" TargetType="{x:Type StackPanel}">
<Setter Property="Margin" Value="20"/>
</Style>
<Style x:Key="HeadingStyle" TargetType="{x:Type Label}">
<Setter Property="FontSize" Value="16"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>
<Style x:Key="CancelButtonStyle" TargetType="{x:Type Button}"/>
</Application.Resources>
</Application>
, CancelButtonStyle ,
. , ,
- .
,
,
!
:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style x:Key="DialogStyle" TargetType="{x:Type StackPanel}">
...
</Style>
<Style x:Key="HeadingStyle" TargetType="{x:Type Label}">
...
</Style>
<Style x:Key="CancelButtonStyle" TargetType="{x:Type Button}">
...
</Style>
...
</ResourceDictionary>
XAML-
Application.Resources.
XAML-, :
ResourceDictionary resources = null;
using (FileStream fs = new FileStream("CustomSkin.xaml",
FileMode.Open, FileAccess.Read))
{
520
14. , ,
// , ResourceDictionary
resources = (ResourceDictionary)XamlReader.Load(fs);
}
Application.Current.Resources = resources;
, URL:
ResourceDictionary resources = null;
System.Net.WebClient client = new System.Net.WebClient();
using (Stream s = client.OpenRead("http://adamnathan.net/wpf/CustomSkin.xaml"))
{
// , ResourceDictionary
resources = (ResourceDictionary)XamlReader.Load(s);
}
Application.Current.Resources = resources;
Application.Current.Resources
, - ResourceDictionary,
,
!
FAQ
, ,
?
Application.Resources , - , ,
,
. ,
.
, . ,
, CancelButtonStyle,
:
System.Windows.ResourceDictionary Warning: 9 : Resource not found;
ResourceKey='CancelButtonStyle'
, -:
/
.
(
http://informit.com/title/9780672331190
)
Cancel. , ,
.
.14.13; .14.14.
521
.14.14.
, Prog
ressBar ( ,
),
.
ProgressBar. , ,
ResourceDictionary
,
. CancelButtonStyle, ,
TranslateTransform, ,
, . ,
Label:
- 1 (
, , ).
,
ProgressBar
( ),
XAML- .
ResourceDictionary
. Application.LoadComponent
,
(. 12).
, :
ResourceDictionary resources = (ResourceDictionary)Application.LoadComponent(
new Uri("CustomSkin.xaml", UriKind.RelativeOrAbsolute));
Application.Current.Resources = resources;
, -
. . .
522
14. , ,
. 14.12 .
14.12.
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- -->
<Style x:Key="DialogStyle" TargetType="{x:Type StackPanel}">
<Setter Property="Margin" Value="0"/>
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Offset="0" Color="LightBlue"/>
<GradientStop Offset="1" Color="White"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Style>
<!-- -->
<Style x:Key="HeadingStyle" TargetType="{x:Type Label}">
<Setter Property="Foreground" Value="White"/>
<Setter Property="FontSize" Value="30"/>
<Setter Property="FontFamily" Value="Segoe Print"/>
<Setter Property="RenderTransform">
<Setter.Value>
<TransformGroup>
<RotateTransform Angle="-35"/>
<TranslateTransform X="-19" Y="55"/>
</TransformGroup>
</Setter.Value>
</Setter>
<Setter Property="Effect">
<Setter.Value>
<DropShadowEffect ShadowDepth="2"/>
</Setter.Value>
</Setter>
</Style>
<!-- Cancel -->
<Style x:Key="CancelButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Visibility" Value="Collapsed"/>
</Style>
<!-- ProgressBar Expander -->
<Style TargetType="{x:Type ProgressBar}">
<Setter Property="Height" Value="100"/>
<Setter Property="Template">
<Setter.Value>
523
DialogStyle HeadingStyle (
,
). ,
, CancelButtonStyle
Cancel! ( , ,
).
,
!
ProgressBar
.
, ProgressBar Expander (
)! Tem
plateBinding, -. ,
ProgressBar null. ,
. Style,
ProgressBar
, Expander Expander Expander ..
FAQ
?
.
,
ResourceDictionary ,
, , -, . ,
- ,
Setter, Visibility.
, ?
, - ?
!
524
14. , ,
. , -
- ,
. ( XAML-!)
.
XAML ,
.
, , ,
,
.
, , ,
.
,
,
. ,
Windows Classic,
. Windows XP
(, , )
.
Windows
WPF (
Button 9 ).
,
. ,
, ,
!
,
. ,
,
, .
,
(, ), .
. , ,
, .
,
, SystemColors, SystemFonts SystemParameters,
Windows. ,
,
.
525
ProgressBar
SystemColors
( . 12):
<Style TargetType="{x:Type ProgressBar}">
<Style.Resources>
<LinearGradientBrush x:Key="foregroundBrush" StartPoint="0,0" EndPoint="1,1">
<GradientStop Offset="0"
Color="{DynamicResource {x:Static SystemColors.InactiveCaptionColorKey}}"/>
<GradientStop Offset="0.5"
Color="{DynamicResource {x:Static SystemColors.InactiveCaptionColorKey}}"/>
<GradientStop Offset="1"
Color="{DynamicResource {x:Static SystemColors.ActiveCaptionColorKey}}"/>
</LinearGradientBrush>
</Style.Resources>
<Setter Property="Foreground" Value="{StaticResource foregroundBrush}"/>
<Setter Property="Background"
Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
...
</Style>
.14.15 Win
dows.
Windows 7 (Aero)
Windows Classic
.14.15.
,
WPF
, .
Windows7 Aero , Windows Classic
. ,
.
,
, .
, - .14.15 ProgressBar Windows
Classic ! ,
, , .
,
, (
, ). WPF
526
14. , ,
,
Win32 WM_THEMECHANGE ( WM_DWMCOMPO
SITIONCHANGED 8 Windows 7). , , WPF
Win32 API
,
.
XAML, .
.
, themes
( !) ThemeName.
ThemeColor.xaml ( ). WPF
. .
Microsoft URI
:
Aero (Windows Vista Windows 7): themes\Aero.NormalColor.xaml
Windows XP : themes\Luna.NormalColor.xaml
Windows XP: themes\Luna.Homestead.xaml
Windows XP: themes\Luna.Metallic.xaml
Windows XP Media Center Edition 2005 Windows XP Tablet PC Edi
tion 2005: themes\Royale.NormalColor.xaml
Windows Classic: themes\Classic.xaml
Zune Windows XP: themes\Zune.NormalColor.xaml
Windows Classic: URI
ThemeColor.
,
, , .
; themes\Gene
ric.xaml.
, .
, .
,
, Theme
InfoAttribute.
ResourceDictionaryLocation. , WPF
, .
:
527
None . .
SourceAssembly .
ExternalAssembly , As
semblyName.ThemeName.dll ( AssemblyName
). WPF ,
PresentationFramework.Aero.dll, PresentationFramework.Luna.dll
..
.
ThemeInfoAttribute :
//
[assembly:ThemeInfo(ResourceDictionaryLocation.SourceAssembly,
ResourceDictionaryLocation.SourceAssembly)]
:
. ThemeInfoAtt
ribute, ,
, .
( ),
, .
,
Button ProgressBar ,
,
ThemeDictionaryExtension.
ThemeDictionaryExtension ,
. ,
, .
ThemeDictionaryExtension
Source ResourceDictionary,
, . :
<Application ...>
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary .../>
<ResourceDictionary Source="{ThemeDictionary MyApplication}"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
, , ProgressBar
Windows. MyApplication
, TargetType {x:Type Progress
Bar}, ProgressBar
ThemeDicti
onaryExtension.
528
14. , ,
, .
20,
. ,
ProgressPie:
public class ProgressPie : ProgressBar
{
static ProgressPie()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(ProgressPie),
new FrameworkPropertyMetadata(typeof(ProgressPie)));
}
}
ProgressPie ProgressBar,
. -
, ,
ProgressBar.
ProgressPie,
DefaultStyleKey.
FrameworkElement FrameworkContentElement
. (
.)
WPF
,
. DefaultStyleKey, ProgressPie
ProgressBar, typeof(ProgressBar).
- ProgressPie typeof(ProgressPie) DefaultStyleKey.
Visual Studio,
ProgressPie, ThemeInfoAtt
ribute , .
XAML-
:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ThemedProgressPie">
<Style TargetType="{x:Type local:ProgressPie}">
...
</Style>
</ResourceDictionary>
.14.16 ProgressPie .
, ,
,
529
. , .14.16, .14.15,
ProgressPie Windows 7 , Win
dows Classic .
, ,
.
Windows 7 (Aero)
Windows Classic
.14.16.
,
Windows
Windows 7 Windows Vista
. Windows
Aero Windows Basic, WPF Aero.NormalColor.
( ,
.) Windows
Standard, Windows Classic - , WPF
Classic. ,
,
SystemColors .
, , ,
WPF.
, ( ) ,
(
), , (,
Button Style null, , ,
).
,
,
. ,
, ,
.
, -
530
14. , ,
(. 20), ,
.
WPF, WPFThemes.zip http://wpf.code
plex.com. , ,
WPF.
, Resources
Application, Window -:
<Application ...>
<Application.Resources>
<ResourceDictionary Source="BureauBlack.xaml"/>
</Application.Resources>
</Application>
, ,
, WPF4, Data
Grid, Calendar DatePicker. .14.17 ,
.
V
V.
15
16
17
18 ,
Drawing
Visual
Shape
15
15.
, , .
- ,
;
Button ProgressBar.
- ,
. ,
. , ,
, , WPF,
, .
WPF; GDI
. WPF GDI
Windows , WPF
, ,
.
(GDI, GDI+, DirectX ..)
,
. ,
, ,
.
, , ,
.
, ,
, : 1010
(0,0), .
, :
1010 (0,0) , .
534
15.
,
.
WPF , ,
, ,
.
WPF,
.
: Drawing, Visual Shape.
. Drawing
Brush
. Visual
Drawing , Visual
,
Drawing. , Shape
Visual, (
) . , Silver
light Shape. Drawing, Visual Shape
,
.
Brush,
.
;
, Foreground Background
. WPF
, . ,
, ,
,
.
Drawing
Drawing . ,
GeometryDrawing, WPF (clip art).
, ,
, Animatable, ,
, !
WPF Drawing:
GeometryDrawing Geometry Brush,
, Pen, .
.
ImageDrawing ImageSource Rect,
.
VideoDrawing MediaPlayer (. 18 ,
) Rect.
535
Drawing
GlyphRunDrawing GlyphRun,
, Brush, .
DrawingGroup Drawing
(Opacity, Transform ).
DrawingGroup Drawing,
, Drawing. ( ,
TransformGroup Transform.)
GeometryDrawing,
Geometry, (EllipseGeometry), Brush
Pen:
<GeometryDrawing Brush="Orange" >
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="10"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<EllipseGeometry RadiusX="100" RadiusY="50"/>
</GeometryDrawing.Geometry>
</GeometryDrawing>
Brush
Pen
Geometry
Drawing UIElement;
. GeometryDrawing
Window ContentControl,
TextBlock, "System.Windows.Media.Geometry
Drawing" ( , ToString).
Drawing ,
-:
DrawingImage ImageSource,
Image BitmapImage.
DrawingBrush Brush,
, Foreground, Background Border
Brush , Control.
DrawingVisual Visual,
Visual.
, DrawingImage
, :
<Image>
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing Brush="Orange">
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="10"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<EllipseGeometry RadiusX="100" RadiusY="50"/>
536
15.
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
.15.1 Image
, GeometryDrawing.
DrawingImage ImageDrawing
, DrawingImage
ImageDrawing. ,
.
DrawingImage ImageSource
Drawing, . , Image
Drawing Drawing, Ima
geSource, .
:
WPF ( ) FooBar
, Bar,
Foo. , DrawingImage ImageSource,
Drawing, ImageDrawing Drawing, ImageSource.
, DrawingImage ImageSource,
. Window.Icon ImageSource,
TaskbarItemInfo.Overlay ThumbButtonInfo.ImageSource (. 8
Windows7). .15.2 , ,
DrawingImage GeometryDrawing
:
<Window ...>
<Window.Icon>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing Brush="Orange">
Drawing
537
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="10"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<EllipseGeometry RadiusX="100" RadiusY="50"/>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingImage.Drawing>
</DrawingImage>
</Window.Icon>
...
</Window>
.15.2. EllipseGeometry
Window, -
, ,
, . Brush
, , Drawing
. .
GeometryDrawing:
Geometry Pen.
Geometry
Geometry .
,
, : ?
?. Geometry ,
.
:
RectangleGeometry Rect,
, RadiusX RadiusY .
EllipseGeometry RadiusX RadiusY, Center.
538
15.
Geometry
Geometry Drawing,
WPF. , System.Windows.Ink.
Stroke Geometry (
GetGeometry), DrawingGroup Visual
Clip,
Geometry.
.
PathGeometry PathFigure
Figures; .
Path
Geometry, . ,
PathGeometry.
PathGeometry.
PathFigure PathSegment. PathFigure Path
Geometry PathSegment
Segments. PathSegment
:
LineSegment .
PolyLineSegment
LineSegment ( ).
ArcSegment .
BezierSegment .
PolyBezierSegment
BezierSegment.
QuadraticBezierSegment .
PolyQuadraticBezierSegment
QuadraticBezierSegment.
( )
.
.
Drawing
539
,
,
. (
), , .
,
, .
, QuadraticBezierSegment
, BezierSegment, .
U- (
), S- .
GeometryDrawing, PathGeometry,
LineSegment, L (.15.3):
<GeometryDrawing>
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="10"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<PathGeometry>
<PathFigure>
<LineSegment Point="0,100"/>
<LineSegment Point="100,100"/>
</PathFigure>
</PathGeometry>
</GeometryDrawing.Geometry>
</GeometryDrawing>
.15.3. GeometryDrawing,
LineSegments
, , .15.3,
GeometryDrawing - Drawing
Image, .
, LineSegment
Point. ,
.
(0,0) (0,100), (0,100) (100,100).
( PathSegment .)
, Start
Point PathFigure Point, (0,0).
540
15.
, ,
. . 15.4 ,
, ,
. 15.4
XAML- Brush:
<GeometryDrawing Brush="Orange">
...
</GeometryDrawing>
.15.4. GeometryDrawing
.15.3,
.15.5. GeometryDrawing
.15.4, IsClosed="True"
,
PathFigure LineSegment
IsClosed PathFigure true.
.15.5.
PathSegment PathFigure
,
Geometry PathGeometry
PathFigure. PathFigure
, PathFigure.
, XAML- , .15.5,
StartPoint,
:
<GeometryDrawing Brush="Orange">
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="10"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<PathGeometry>
<!-- 1 -->
<PathFigure IsClosed="True">
<LineSegment Point="0,100"/>
<LineSegment Point="100,100"/>
</PathFigure>
<!-- 2 -->
<PathFigure StartPoint="70,0" IsClosed="True">
<LineSegment Point="0,100"/>
<LineSegment Point="100,100"/>
</PathFigure>
</PathGeometry>
</GeometryDrawing.Geometry>
</GeometryDrawing>
541
Drawing
GeometryDrawing PathFigure
.15.6. ,
LineSegment true IsSmoothJoin (
PathSegment). . 15.6 ,
.
XAML
IsSmoothJoin="True"
LineSegments
.15.6. ,
PathFigures
, , .
PathGeometry
FillRule.
FillRule.
,
PathFigure PathSegment
PathFigure,
( ) .
FillRule PathGeometry (
FillRule), :
EvenOdd ,
, ,
. .
NonZero ,
, ,
.
.
EvenOdd NonZero .15.7
, .15.6.
EvenOdd
NonZero
.15.7.
PathGeometry.FillRule
542
15.
WPF
GeometryGroup CombinedGeometry ,
. , ,
TransformGroup Transform, DrawingGroup Drawing,
Geometry,
, Geometry.
StreamGeometry
,
, StreamGeometry, Path
Geometry . StreamGeometry
, PathGeometry, .
:
( ), PathFigure Path
Segment , .NET.
StreamGeometry
, .15.6:
StreamGeometry g = new StreamGeometry();
using (StreamGeometryContext context = g.Open())
{
// 1
context.BeginFigure(new Point(0, 0), true /*isFilled*/, true /*isClosed*/);
context.LineTo(new Point(0, 100), true /*isStroked*/, true /*isSmoothJoin*/);
context.LineTo(new Point(100, 100), true /*isStroked*/, true /*isSmoothJoin*/);
// 2
context.BeginFigure(new Point(70, 0), true /*isFilled*/, true /*isClosed*/);
context.LineTo(new Point(0, 100), true /*isStroked*/, true /*isSmoothJoin*/);
context.LineTo(new Point(100, 100), true /*isStroked*/, true /*isSmoothJoin*/);
}
// Geometry
// GeometryDrawing:
geometryDrawing.Geometry = g;
GeometryGroup. GeometryGroup
Geometry. , XAML-
.15.6
(
PathFigure) :
Drawing
543
<GeometryDrawing Brush="Orange">
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="10"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<GeometryGroup>
<!-- 1 -->
<PathGeometry>
<PathFigure IsClosed="True">
<LineSegment Point="0,100"/>
<LineSegment Point="100,100"/>
</PathFigure>
</PathGeometry>
<!-- 2 -->
<PathGeometry>
<PathFigure StartPoint="70,0" IsClosed="True">
<LineSegment Point="0,100"/>
<LineSegment Point="100,100"/>
</PathFigure>
</PathGeometry>
</GeometryGroup>
</GeometryDrawing.Geometry>
</GeometryDrawing>
544
15.
<!-- 2 -->
<PathGeometry>
<PathGeometry.Transform>
<RotateTransform Angle="25"/>
</PathGeometry.Transform>
<PathFigure IsClosed="True">
<LineSegment Point="0,100" IsSmoothJoin="True"/>
<LineSegment Point="100,100" IsSmoothJoin="True"/>
</PathFigure>
</PathGeometry>
</GeometryGroup>
</GeometryDrawing.Geometry>
</GeometryDrawing>
.15.8.
PathGeometry PathFigure .
PathGeometry PathFigure,
.
GeometryGroup .
.15.8. GeometryGroup
,
UIElement, ,
Geometry, PathFigure
.
, .
,
.
Drawing
545
GeometryGroup, .15.8,
PathFigure .
PathFigure figure GeometryGroup
:
<GeometryGroup>
<!-- 1 -->
<PathGeometry>
<StaticResource ResourceKey="figure"/>
</PathGeometry>
<!-- 2 -->
<PathGeometry>
<PathGeometry.Transform>
<RotateTransform Angle="25"/>
</PathGeometry.Transform>
<StaticResource ResourceKey="figure"/>
</PathGeometry>
546
15.
<CombinedGeometry.Geometry2>
<!-- 2 -->
<PathGeometry>
...
</PathGeometry>
</CombinedGeometry.Geometry2>
</CombinedGeometry>
</GeometryDrawing.Geometry>
</GeometryDrawing>
Union
Intersect
Xor
Exclude
.15.9. CombinedGeometry
GeometryCombineMode;
Geometry
, ,
.
XAML- ,
- , ,
.
WPF GeometryConverter,
,
PathGeometry . Geometry
Parse,
Geometry. ( , ,
, Geometry.Parse,
StreamGeometry,
.)
, PathGeometry,
.15.6:
<GeometryDrawing>
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="10"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<PathGeometry>
<PathFigure IsClosed="True">
547
Drawing
<LineSegment Point="0,100"/>
<LineSegment Point="100,100"/>
</PathFigure>
</PathGeometry>
</GeometryDrawing.Geometry>
</GeometryDrawing>
:
<GeometryDrawing Geometry="M 0,0 L 0,100 L 100,100 Z">
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="10"/>
</GeometryDrawing.Pen>
</GeometryDrawing>
.15.6
:
<GeometryDrawing Geometry="M 0,0 L 0,100 L 100,100 Z M 70,0 L 0,100 L 100,100 Z">
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="10"/>
</GeometryDrawing.Pen>
</GeometryDrawing>
, Path
Geometry PathFigure, .
, . .15.1
.
15.1.
PathGeometry PathFigure
F n
M x,y
PathSegment
L x,y
LineSegment, (x,y).
A rx,ry d f1 f2
x,y
ArcSegment, (x,y)
rx ry,
d . f1 f2 0 (false) 1
(true) ArcSegment: IsLargeArc (
) Clockwise ( ).
548
15.
15.1 ()
BezierSegment, (x,y),
(x1,y1)
(x2,y2). C cubic ( ).
Q x1,y1 x,y
QuadraticBezierSegment,
(x,y),
(x1,y1).
H x
LineSegment, (x,y), y
. H horizontal
( ).
V y
LineSegment, (x,y), x
. V vertical
( ).
S x2,y2 x,y
BezierSegment,
(x,y),
(x1,y1) (x2,y2). x1 y1 ,
. (
, ,
BezierS egment.)
S smooth ( ).
,
,
. F, M Z ,
.
,
,
. , M 0,0 L 0,100 L 100,100 Z
M0 0L0 100L100 100Z, .
Pen
GeometryDrawing
, ( Pen)
. , , ,
Thickness. , Pen,
, : Brush ( Brush) Thickness ( double).
Drawing
549
Pen
:
StartLineCap EndLineCap
, PenLineCap: Flat (
, ), Square, Round Triangle.
LineJoin.
LineJoin .
PenLineJoin: Miter ( ),
Round Bevel. MiterLimit ,
Miter; ,
.
10.
DashStyle , (
). DashStyle.
DashCap
Pen; StartLineCap EndLineCap,
Square, Flat.
FAQ
Flat Square
PenLineCap?
Flat , Square
. ,
, . ,
.
. 15.10 PenLineCap,
LineSegment. .15.11
LineJoin . Round
LineJoin , true IsSmoothJoin
PathSegment.
, LineJoin
.
Flat
Square
Round
Triangle
.15.10. PenLineCap,
550
15.
Miter
Round
Bevel
.15.11. LineJoin
.15.12 DashStyles
Dashes.
Solid
Dash (2,2)
Dot (0,2)
DashDot (2,2,0,2)
DashDotDot
(2,2,0,2,0,2)
.15.12. ,
DashCap Miter: Square LineJoin
, GeometryDrawing,
. 15.1 DrawingGroup,
Drawing
551
Image, GeometryDrawing,
(.15.13).
15.1. Drawing,
Image
<Image>
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<DrawingGroup>
<!-- -->
<GeometryDrawing Brush="Blue" Geometry="M 240,250
C 200,375 200,250 175,200
C 100,400 100,250 100,200
C 0,350 0,250 30,130
C 75,0 100,0 150,0
C 200,0 250,0 250,150 Z"/>
<!-- -->
<GeometryDrawing Brush="Black">
<GeometryDrawing.Pen>
<Pen Brush="White" Thickness="10"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<GeometryGroup>
<!-- -->
<EllipseGeometry RadiusX="15" RadiusY="15" Center="95,95"/>
<!-- -->
<EllipseGeometry RadiusX="15" RadiusY="15" Center="170,105"/>
</GeometryGroup>
</GeometryDrawing.Geometry>
</GeometryDrawing>
<!-- -->
<GeometryDrawing>
<GeometryDrawing.Pen>
<Pen Brush="Black" StartLineCap="Round"
EndLineCap="Round" Thickness="10"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<LineGeometry StartPoint="75,160" EndPoint="175,150"/>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
552
15.
.15.13. , DrawingGroup,
GeometryDrawing
Visual
Visual, UIElement (
FrameworkElement),
.
Drawing Image. Image
Visual, ,
FrameworkElement UIElement, ,
, , ,
, , ,
, ,
..
,
, -
Bing Maps.
WPF,
Drawing.
Image,
.
Image, ,
, .
, Visual ,
Drawing : DrawingVisual.
, Opacity Clip ( , ,
DrawingGroup).
( Visual).
DrawingVisual
, WPF,
. , DrawingVisual ,
Visual.
Visual
553
DrawingVisual
DrawingVisual Drawing,
Drawing (, - ,
).
RenderOpen, DrawingContext.
, Close.
, Drawing
15.1 DrawingVisual ,
ghostDrawing:
DrawingGroup ghostDrawing = FindResource("ghostDrawing") as DrawingGroup;
DrawingVisual ghostVisual = new DrawingVisual();
using (DrawingContext dc = ghostVisual.RenderOpen())
{
dc.DrawDrawing(ghostDrawing);
}
, DrawingContext
IDisposable Close Dispose (
finally using).
15.1 GeometryDrawing, ,
DrawingGroup ,
Drawing,
DrawingImage. DrawingVisual Geometry
Drawing . Geomet
ryDrawing DrawingContext , ,
:
GeometryDrawing bodyDrawing = FindResource("bodyDrawing") as GeometryDrawing;
GeometryDrawing eyesDrawing = FindResource("eyesDrawing") as GeometryDrawing;
GeometryDrawing mouthDrawing = FindResource("mouthDrawing") as GeometryDrawing;
DrawingVisual ghostVisual = new DrawingVisual();
using (DrawingContext dc = ghostVisual.RenderOpen())
{
dc.DrawDrawing(bodyDrawing);
dc.DrawDrawing(eyesDrawing);
dc.DrawDrawing(mouthDrawing);
}
,
Z-.
DrawingGroup,
Drawing! Drawing
, DrawingContext.
DrawingContext
, . ( ,
,
Drawing: GeometryDrawing, ImageDrawing, VideoDrawing
554
15.
GlyphRunDrawing.)
. DrawingContext .15.2.
15.2. DrawingContext
PushClip, PushEffect,
PushGuidelineSet, PushOpacity,
PushOpacityMask, PushTransform,
Pop
Close
PushXXX Pop ,
, ,
. WPF4 PushEffect
, , .
15.2
15.1 . Window
DrawingVisual, Drawing.
, Window, ,
, Drawing
Visual! .
15.2. WindowHostingVisual.cs
15.1 DrawingContext
using System;
using System.Windows;
using System.Windows.Media;
public class WindowHostingVisual : Window
{
public WindowHostingVisual()
{
Title = "Hosting DrawingVisuals";
Width = 300;
Height = 350;
DrawingVisual ghostVisual = new DrawingVisual();
using (DrawingContext dc = ghostVisual.RenderOpen())
{
Visual
555
//
dc.DrawGeometry(Brushes.Blue, null, Geometry.Parse(
@"M 240,250
C 200,375 200,250 175,200
C 100,400 100,250 100,200
C 0,350 0,250 30,130
C 75,0 100,0 150,0
C 200,0 250,0 250,150 Z"));
//
dc.DrawEllipse(Brushes.Black, new Pen(Brushes.White, 10),
new Point(95, 95), 15, 15);
//
dc.DrawEllipse(Brushes.Black, new Pen(Brushes.White, 10),
new Point(170, 105), 15, 15);
//
Pen p = new Pen(Brushes.Black, 10);
p.StartLineCap = PenLineCap.Round;
p.EndLineCap = PenLineCap.Round;
dc.DrawLine(p, new Point(75, 160), new Point(175, 150));
}
}
}
DrawGeometry
.
Geometry.Parse
, 15.1,
PathFigure, BezierSegment.
Geometry;
DrawEllipse DrawLine. , ,
, Pen
, .
XAML- 15.1, 15.2
.
.
,
DrawGeometry DrawingContext ,
, , , DrawText
. ,
, DrawImage
,
Image . (
DrawImage ImageSource, Image.)
, DrawingContext WPF
Win32 Graphics Windows Forms. ,
DrawingContext ,
.
; WPF , .
556
15.
DrawingContext
,
Drawing, , ..
.
Visual
Visual, UIEle
ment, ;
Content , Window,
,
,
, OnRender. Visual,
UIElement, DrawingVisual
,
, ToString.
Visual ,
- UIElement.
: , ! - ,
DrawingVisual ,
, UIElement! - ,
UIElement - , .
Visual
Canvas Window,
UIElement.
Visual ,
- UIElement
: VisualChildrenCount GetVisualChild.
15.3 Window,
15.2. , ,
DrawingVisual, . 15.14. ,
, DrawingImage Image.
15.3. WindowHostingVisual.cs ,
using System;
using System.Windows;
using System.Windows.Media;
public class WindowHostingVisual : Window
{
DrawingVisual ghostVisual = null;
Visual
public WindowHostingVisual()
{
Title = "Hosting DrawingVisuals";
Width = 300;
Height = 350;
ghostVisual = new DrawingVisual();
using (DrawingContext dc = ghostVisual.RenderOpen())
{
, 15.2...
}
// :
AddVisualChild(ghostVisual);
AddLogicalChild(ghostVisual);
}
// ,
// Visual:
protected override int VisualChildrenCount
{
get { return 1; }
}
protected override Visual GetVisualChild(int index)
{
if (index != 0)
throw new ArgumentOutOfRangeException("index");
return ghostVisual;
}
}
.15.14. DrawingVisual, ,
,
VisualChildrenCount GetVisualChild
557
558
15.
VisualChildrenCount Visual,
Window.
DrawingVisual, 1. GetVisualChild
Visual ( 0).
DrawingVisual, 0,
.
Visual,
, .
, MeasureOverride
ArrangeOverride; 21
.
, VisualChildrenCount/GetVisualChild,
15.3, Content
Window, . ,
Visual - ,
UIElement, , .
, ,
Visual , Canvas,
Grid ( ) Window,
.
15.3
: DrawingVisual ,
Window: AddVisualChild (
Visual) AddLogicalChild ( FrameworkElement).
DrawingVisual, , ,
,
. ,
, ,
, .
Visual ,
RemoveVisualChild RemoveLogicalChild.
Visual
Visual, UIElement,
UIElement, , .
Visual ,
- UIElement. , Visual
PrintVisual PrintDialog
Win32 ( 19
). DrawingVisual RenderTargetBitmap,
.
Visual
559
Visual.AddVisualChild!
AddVisualChild ,
Visual. .
VisualChildrenCount GetVisualChild.
Drawing
Visual, ,
,
UIElement. UIElement,
DrawingVisual. UIElement
, DrawingVisual: OnRender,
, DrawingContext,
- ,
Content ContentControl. , , ,
Drawing Image ,
UIElement .
Visual
(hit testing) ,
( ) .
, ,
, , .
WPF : Visual,
, Visual,
, UIElement.
Visual,
Shape.
Visual
, ,
, ,
UIElement (MouseLeftButtonDown, MouseEnter, MouseLeave, MouseMove
). - UIElement
Visual, ,
- Visual,
.
560
15.
Visual
VisualTreeHelper.HitTest.
Visual, ,
(
). HitTestResult,
Visual , .
, 15.3
( DrawingVisual),
1 ( ):
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
//
Point location = e.GetPosition(this);
//
HitTestResult result = VisualTreeHelper.HitTest(this, location);
// ghostVisual,
if (result.VisualHit == ghostVisual)
{
if (ghostVisual.Transform == null)
ghostVisual.Transform = new RotateTransform();
(ghostVisual.Transform as RotateTransform).Angle++;
}
}
Image Visual,
,
DrawingImage, Image ( 15.1). (
MouseLeftButtonDown Image.)
Image
DrawingVisual. ,
DrawingVisual,
- . Image
, -
, .
Visual
, , , ,
: , .
DrawingVisual . 15.4
Visual
561
1 , . .15.15
,
.
15.4. WindowHostingVisual.cs
DrawingVisual
using
using
using
using
using
System;
System.Windows;
System.Windows.Input;
System.Windows.Media;
System.Collections.Generic;
562
15.
using (DrawingContext dc = mouthVisual.RenderOpen())
{
//
Pen p = new Pen(Brushes.Black, 10);
p.StartLineCap = PenLineCap.Round;
p.EndLineCap = PenLineCap.Round;
dc.DrawLine(p, new Point(75, 160), new Point(175, 150));
}
visuals.Add(bodyVisual);
visuals.Add(eyesVisual);
visuals.Add(mouthVisual);
// :
foreach (Visual v in visuals)
{
AddVisualChild(v);
AddLogicalChild(v);
}
}
// ,
// Visual:
protected override int VisualChildrenCount
{
get { return visuals.Count; }
}
protected override Visual GetVisualChild(int index)
{
if (index < 0 || index >= visuals.Count)
throw new ArgumentOutOfRangeException("index");
return visuals[index];
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
//
Point location = e.GetPosition(this);
// Visual
HitTestResult result = VisualTreeHelper.HitTest(this, location);
// - DrawingVisual,
if (result.VisualHit.GetType() == typeof(DrawingVisual))
{
DrawingVisual dv = result.VisualHit as DrawingVisual;
if (dv.Transform == null)
dv.Transform = new RotateTransform();
Visual
563
(dv.Transform as RotateTransform).Angle++;
}
}
}
.15.15. ,
DrawingVisual,
Visual, ,
List<Visual> Visual
ChildrenCount GetVisualChild. DrawingVisual
, : Draw
ingContext using, DrawingVisual.
HitTestResult
DrawingVisual, .
DrawingVisual DrawingVisual
DrawingVisual ContainerVisual,
- Children
Visual. ( ContainerVisual VisualGroup
WPF, TransformGroup, DrawingGroup GeometryGroup.)
15.4
eyesVisual mouthVisual bodyVisual,
visuals. ,
, - Visual, !
DrawingVisual, ContainerVisual VisualChildrenCount
GetVisualChild , 15.4.
Window DrawingVisual DrawingVisual
!
564
15.
Visual
Visual
Visual, ,
. , Visual,
,
, .
Visual ,
.
,
HitTest, HitTestResultCallback.
HitTest ,
Visual,
.
OnMouseLeftButtonDown
15.4
Visual:
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
//
Point location = e.GetPosition(this);
// Visual
VisualTreeHelper.HitTest(this, null,
new HitTestResultCallback(HitTestCallback),
new PointHitTestParameters(location));
}
public HitTestResultBehavior HitTestCallback(HitTestResult result)
{
// - DrawingVisual,
if (result.VisualHit.GetType() == typeof(DrawingVisual))
{
DrawingVisual dv = result.VisualHit as DrawingVisual;
if (dv.Transform == null)
dv.Transform = new RotateTransform();
(dv.Transform as RotateTransform).Angle++;
}
//
return HitTestResultBehavior.Continue;
}
.
, HitTestResult
, HitTest
Visual
565
.
HitTestResultBehavior: Continue Stop. ,
Visual.
Stop,
Visual, ,
, .
HitTest, null,
HitTestFilterCallback,
, .
.
, HitTest Point
, PointHitTestParameters. ,
HitTestParameters,
WPF : PointHitTestParameters GeometryHitTestPara
meters.
.
,
.
FAQ
,
HitTestResult?
.
WPF ,
, Visual
. ,
,
, HitTestResultBehavior.Stop.
, Visual,
,
, ,
HitTestCore Visual,
. (
.)
Visual
,
. Visual
: ,
.
566
15.
!
,
.
,
,
HitTest. ,
HitTest ,
.
Shape
Shape, GeometryDrawing, ,
Geometry Pen Brush. , Geometry
Drawing, Shape FrameworkElement
. ,
2 XAML ,
Button , Rectangle (
Shape):
<Button MinWidth="75">
<Rectangle Height="20" Width="20" Fill="Black"/>
</Button>
WPF ,
System.Windows.Shapes.Shape:
Rectangle
Ellipse
Line
Polyline
Polygon
Path
,
Geometry.
, ,
Geometry. ( , Polyline Polygon
Shape , PathGeometry.)
Shape
. Fill
Stroke, Brush.
Shape
567
FAQ
Shape.Stroke Brush, Pen?
Fill Stroke Shape , Brush Pen
GeometryDrawing: Fill
, Stroke .
Shape Pen.
, Shape Stroke
Brush
, Stroke: StrokeStartLineCap, StrokeEndLineCap,
StrokeThickness ..
,
Shape ,
Pen, ,
Brush Thickness.
Shape
!
Shape ,
. ,
Drawing, ,
WPF . ,
XAML
Shape ,
. ,
Microsoft Expression Design XAML Export,
XAML- Shape
Canvas, Document Format
Resource Dictionary. DrawingImage
DrawingBrush. DrawingImage ,
, ,
.
Shape,
, , , ,
, .. , ,
, ,
Visual ,
. ,
Shape.
568
15.
Rectangle
RectangleGeometry Rect,
. Rectangle
WPF. Width Height,
( ) FrameworkElement, , ,
Canvas.Left Canvas.Top.
, RectangleGeometry, Rectangle
RadiusX RadiusY double,
. .15.16
StackPanel RadiusX RadiusY:
<StackPanel>
<Rectangle Width="200" Height="100"
Fill="Orange" Stroke="Black" StrokeThickness="10" Margin="4"/>
<Rectangle Width="200" Height="100" RadiusX="10" RadiusY="30"
Fill="Orange" Stroke="Black" StrokeThickness="10" Margin="4"/>
<Rectangle Width="200" Height="100" RadiusX="30" RadiusY="10"
Fill="Orange" Stroke="Black" StrokeThickness="10" Margin="4"/>
<Rectangle Width="200" Height="100" RadiusX="100" RadiusY="50"
Fill="Orange" Stroke="Black" StrokeThickness="10" Margin="4"/>
</StackPanel>
RadiusX Width , Ra
diusY Height.
.
RadiusX=10, RadiusY=30
RadiusX=30, RadiusY=10
.15.16.
RadiusX RadiusY
Shape
569
Shape , Stroke
Fill!
, GeometryDrawing,
, , Shape
, Button ListBox, .
Shape Geometry,
Stroke Fill null.
Ellipse
Rectangle ,
( ), , , , Ellipse
. ! Ellipse
.
,
Shape . EllipseGeometry,
RadiusX, RadiusY Center, Ellipse
.
Ellipse
Rectangle XAML, .15.16
:
<Ellipse Width="200" Height="100"
Fill="Orange" Stroke="Black" StrokeThickness="10" Margin="4"/>
RadiusX RadiusY.
Shape
Shape OnRender UIElement
DrawingContext.
, Ellipse OnRender
:
protected override void OnRender(DrawingContext drawingContext)
{
Pen pen = ...; // StrokeXXX
Rect rect = ...; //
drawingContext.DrawGeometry(this.Fill, pen, new EllipseGeometry(rect));
}
Rectangle OnRender :
570
15.
Shape ,
. 21.
Line
Line double,
, (x1,y1) (x2,y2). X1, Y1,
X2, Y2. ,
Point ( LineGeometry),
.
, Line, ,
, Line
. , StackPanel ,
.15.17:
<StackPanel>
<Line X1="0" Y1="0" X2="100" Y2="100" Stroke="Black"
StrokeThickness="10" Margin="4"/>
<Line X1="0" Y1="0" X2="100" Y2="0" Stroke="Black"
StrokeThickness="10" Margin="4"/>
<Line X1="0" Y1="100" X2="100" Y2="0" Stroke="Black"
StrokeThickness="10" Margin="4"/>
</StackPanel>
(0,0) (100,100)
(0,0) (100,0)
(0,100) (100,0)
.15.17. StackPanel ,
,
, 10
( Stroke) Margin. Line
Shape
571
Shape Fill, ,
.
Polyline
Polyline () ,
Points ( Point). .15.18
Polyline:
<StackPanel>
<Polyline Points="0,0 100,100" Stroke="Black" StrokeThickness="10" Margin="4"/>
<Polyline Points="0,0 100,100 200,0" Stroke="Black"
StrokeThickness="10" Margin="4"/>
<Polyline Points="0,0 100,100 200,0 300,100"
Stroke="Black" StrokeThickness="10" Margin="4"/>
<Polyline Points="0,0 100,100 200,0 300,100 100,100"
Stroke="Black" StrokeThickness="10" Margin="4"/>
</StackPanel>
Point
x y.
.
.
.15.18.
2 5
.15.19. , .15.18,
Fill
572
15.
Polygon
Rectangle Ellipse, Polyline
Polygon. Polyline Polygon
, Polygon ,
. ( ,
true IsClosed PathFigure,
PathGeometry.)
Polyline, .15.19,
Polygon, , .15.20.
,
, .15.19. -
Miter ,
( ). 0,
, Stroke
MiterLimit 10 .
Path
, , , Shape
Path ,
PathGeometry. Path
Shape Data,
Shape
573
. , Path (
)
. Drawing
DrawingContext;
Data, Fill , Stroke.
Path ,
.15.6:
<Path Fill="Orange" Stroke="Black" StrokeThickness="10">
<Path.Data>
<PathGeometry>
<!-- 1 -->
<PathFigure IsClosed="True">
<LineSegment Point="0,100"/>
<LineSegment Point="100,100"/>
</PathFigure>
<!-- 2 -->
<PathFigure StartPoint="70,0" IsClosed="True">
<LineSegment Point="0,100"/>
<LineSegment Point="100,100"/>
</PathFigure>
</PathGeometry>
</Path.Data>
</Path>
, Geometry,
:
<Path Fill="Orange" Stroke="Black" StrokeThickness="10"
Data="M 0,0 L 0,100 L 100,100 Z M 70,0 L 0,100 L 100,100 Z"/>
, Shape
, 15.1
DrawingImage, 15.2 15.4
DrawingContext. 15.5
, Shape,
Canvas.
DrawingImage, Image, .15.13.
15.5. ,
<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Path Fill="Blue" Data="M 240,250
C 200,375 200,250 175,200
C 100,400 100,250 100,200
C 0,350 0,250 30,130
C 75,0 100,0 150,0
C 200,0 250,0 250,150 Z"/>
<Ellipse Fill="Black" Stroke="White" StrokeThickness="10"
574
15.
Path () Line () ,
DrawingImage.
EllipseGeometry Ellipse .
15 10.
,
20 . 15.5
Ellipse Height Width, 40 (,
2). Shape
. ,
Canvas.Left Canvas.Top, EllipseGeometry Center
20.
,
(
!),
UIElement.
Visual: ,
,
. ,
, ,
IsEnabled IsVisible ( UIElement) true. (
, ,
,
, .)
-,
Visual. InputHitTest Visual
TreeHelper.HitTest,
! ,
UIElement,
, .
, InputHitTest
UIElement, .
Point, IInputElement (
, UIElement ContentElement).
575
,
UIElement ,
(, ): GotKeyboardFocus,
KeyDown, KeyUp, GotMouseCapture, MouseEnter, MouseLeave, MouseMove, MouseWheel, Got
StylusCapture, StylusEnter, StylusLeave, StylusInAirMove ..
,
Shape Visual.
WPF XAML, ,
WPF
. , ,
(Brush).
, WPF ,
. ,
, (BitmapCacheBrush).
Drawing Window, ,
,
, .
WPF SolidColorBrush, LinearGra
dientBrush RadialGradientBrush. , , ,
,
. ,
.
SolidColorBrush
SolidColorBrush,
, . Color
System.Windows.Media.Color. ,
Blue #FFFFFF SolidColorBrush,
XAML- Color.
Color ,
. :
sRGB RGB, -
-.
, ,
256 .
scRGB RGB, ,
.
.
576
15.
0.0, ;
1.0, . scRGB
, ,
-
. scRGB
, .
Color ( )
: A, R, G, B Byte
sRGB, ScA, ScR, ScG, ScB Single
scRGB. (A ScA -
.)
Color. ,
Color
. ,
sRGB scRGB
.
,
-, Opacity,
.
Color , ,
. ,
scRGB (
),
AreClose, true,
.
Color
:
, Red, Khaki DodgerBlue (
Colors).
sRGB- #argb, a, r, g b
A, R, G, B. ,
#FFFF0000 #FF0000 (
, A 255).
scRGB- sc#a, r g b, a, r, g b
ScA, ScR, ScG, ScB.
sc#1.0 1.0 0.0 0.0 sc#1.0 0.0 0.0.
,
.
577
,
ICC-. (ICC (International Color Consortium)
,
.) Color ,
Color.FromValues,
Single Uri, . XAML
Color,
ContextColor Uri .
, SolidColorBrush
, sRGB-,
system32\spool\drivers\color , Windows:
<Button>
<Button.Background>
<SolidColorBrush Color="ContextColor
file://C:/Windows/system32/spool/drivers/color/sRGB%20Color%20Space%20Profile.icm
1.0,1.0,0.0,0.0"/>
</Button.Background>
</Button>
,
.
. - ,
BitmapSource BitmapCreateOptions.IgnoreColorProfile,
.
LinearGradientBrush
LinearGradientBrush,
, .
.
LinearGradientBrush GradientStops,
GradientStop.
Color Offset. Offset double;
, 0 , 1 . ,
LinearGradientBrush
, , .15.21:
<LinearGradientBrush>
<GradientStop Offset="0" Color="Blue"/>
<GradientStop Offset="1" Color="Red"/>
</LinearGradientBrush>
578
15.
.15.21. -
(. )
.
StartPoint EndPoint LinearGradientBrush.
Offset GradientStop. ,
StartPoint EndPoint (0,0) (1,1) .
,
, MappingMode Absolute (
RelativeToBoundingBox). ,
StartPoint EndPoint;
Offset GradientStop .
. 15.22 , StartPoint
EndPoint LinearGradientBrush,
.15.21 ( MappingMode).
, 0 1.
, ,
. (
GradientStop Offset.)
sRGB,
scRGB, ColorInterpolation
Mode ScRgbLinearInterpolation.
(.15.23).
LinearGradientBrush SpreadMe
thod; , ,
. , LinearGradientBrush
, .
Pad ( Gradi
entSpreadMethod); , ,
. Repeat Reflect.
, Reflect
, .
. 15.24 SpreadMethod -
579
, 10%
:
<LinearGradientBrush StartPoint=".45,.45" EndPoint=".55,.55" SpreadMethod="XXX">
<GradientStop Offset="0" Color="Blue"/>
<GradientStop Offset="1" Color="Red"/>
</LinearGradientBrush>
StartPoint = (0,0),
EndPoint = (0,1)
StartPoint = (0,1),
EndPoint = (0,0)
StartPoint = (0.5,0),
EndPoint = (1,0)
StartPoint = (0,0),
EndPoint = (1,0)
StartPoint = (2,2),
EndPoint = (2,2)
SRgbLinearInterpolation
ScRgbLinearInterpolation
.15.23. ColorInterpolationMode
(. )
580
15.
Pad
Repeat
Reflect
.15.24. SpreadMethod
(. )
,
, Drawing, Shape, Control
. . 15.25 ,
GeometryDrawing, , :
<Pen Thickness="20">
<Pen.Brush>
<LinearGradientBrush>
<GradientStop Offset="0" Color="Red"/>
<GradientStop Offset="0.2" Color="Orange"/>
<GradientStop Offset="0.4" Color="Yellow"/>
<GradientStop Offset="0.6" Color="Green"/>
<GradientStop Offset="0.8" Color="Blue"/>
<GradientStop Offset="1" Color="Purple"/>
</LinearGradientBrush>
</Pen.Brush>
</Pen>
, , , ,
GradientStop,
.
.15.25. -
(. )
581
,
GradientStop Offset,
Color. 0.2 0.6
, ,
DarkBlue:
<LinearGradientBrush EndPoint="0,1">
<GradientStop Offset="0" Color="Aqua"/>
<GradientStop Offset="0.2" Color="Blue"/>
<GradientStop Offset="0.2" Color="DarkBlue"/>
<GradientStop Offset="0.6" Color="DarkBlue"/>
<GradientStop Offset="0.6" Color="Blue"/>
<GradientStop Offset="1" Color="Aqua"/>
</LinearGradientBrush>
.15.26 .
.15.26. ,
Offset (. )
RadialGradientBrush
RadialGradientBrush LinearGradientBrush,
,
. Gra
dientBrush, GradientStops, SpreadMethod, ColorIn
terpolationMode MappingMode, LinearGra
dientBrush.
.15.27
- :
<RadialGradientBrush>
<GradientStop Offset="0" Color="Blue"/>
<GradientStop Offset="1" Color="Red"/>
</RadialGradientBrush>
582
15.
.15.27. -
(. )
,
, .
, SpreadMethod, Repeat
(.15.28).
Radi
alGradientBrush Center, RadiusX RadiusY.
(0.5,0.5), 0.5 0.5 ,
.
( .15.28),
, SpreadMethod, .
RadialGradientBrush GradientOrigin,
. ,
. (0.5,0.5),
, .15.29 , ,
(0,0):
<RadialGradientBrush GradientOrigin="0,0" SpreadMethod="Repeat">
<GradientStop Offset="0" Color="Blue"/>
583
.15.29.
GradientOrigin (. )
MappingMode, Absolute,
- (Center, RadiusX, RadiusY, GradientOri
gin) ,
.
Color -,
, -
GradientStop. , -
-:
<RadialGradientBrush RadiusX="0.7" RadiusY="0.7">
<GradientStop Offset="0" Color="#990000FF"/>
<GradientStop Offset="1" Color="#000000FF"/>
</RadialGradientBrush>
.15.30 (
!) , ,
.
.15.30. ,
- (. )
584
15.
, !
, GradientStop .15.30
, Transparent. , Tran
sparent - (#00FFFFFF).
, -.
GradientStop Transparent,
0x99 0,
0 0xFF. .
WPF ,
TileBrush.
.
Drawing, Image Visual.
,
.
DrawingBrush.
: ImageBrush VisualBrush.
DrawingBrush
Drawing DrawingBrush
DrawingImage. XAML-
DrawingGroup 15.1
Drawing DrawingImage,
:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="DrawingBrush as the Background">
<Window.Background>
<DrawingBrush>
<DrawingBrush.Drawing>
<DrawingGroup>
GeometryDrawing 15.1...
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Window.Background>
</Window>
. 15.31 . DrawingImage,
DrawingBrush ,
.
585
.15.31. , DrawingBrush,
(
, ),
Stretch,
, Stretch (
5 Viewbox).
.15.32 .
None
Fill ( )
Uniform
UniformToFill
586
15.
587
TileMode, TileMode,
Tile None. ,
:
FlipX
.
FlipY
.
FlipXY .
.15.34 .
,
.
, , Viewbox,
( , TileMode
None) Drawing. Viewbox
,
, Viewport. ViewboxUnits
Viewbox
ViewportUnits.
FlipX
FlipY
FlipXY
.15.34. ,
TileMode
588
15.
.15.35 Viewbox
Drawing, Rect 0, 0, 0.5, 0.5.
TileMode.
Tile
FlipXY
.15.35. Viewbox ,
.
TileMode
DrawingBrush: ,
Drawing GeometryDrawing.
, , VideoDrawing!
ImageBrush
ImageBrush DrawingBrush , :
ImageSource ImageSource, Drawing Drawing.
, . (
, DrawingImage ImageDrawing,
, DrawingBrush ,
ImageBrush !)
XAML- ImageBrush
Window. Winter Leav
es.jpg, Windows Vista:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="ImageBrush with TileMode = FlipXY">
<Window.Background>
<ImageBrush TileMode="FlipXY" Viewport="0,0,0.1,0.2">
<ImageBrush.ImageSource>
<BitmapImage UriSource="C:\Users\Public\Pictures\Sample Pictures\Winter
Leaves.jpg"/>
</ImageBrush.ImageSource>
</ImageBrush>
</Window.Background>
</Window>
589
.15.36 .
VisualBrush
VisualBrush DrawingBrush , ,
Drawing Drawing Visual Visual.
Visual,
FrameworkElement, Button TextBox, Visu
alBrush .
XAML- VisualBrush,
Button. .15.37
.
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="ImageBrush with TileMode = FlipXY">
<Window.Background>
<VisualBrush TileMode="FlipXY" Viewport="0,0,0.5,0.5">
<VisualBrush.Visual>
<Button>OK</Button>
</VisualBrush.Visual>
</VisualBrush>
</Window.Background>
</Window>
590
15.
.15.37. VisualBrush
VisualBrush,
Visual UIElement,
.
, ,
:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="VisualBrush with TileMode = FlipXY">
<DockPanel>
<StackPanel Margin="10" x:Name="stackPanel">
<Button>Button</Button>
<CheckBox>CheckBox</CheckBox>
</StackPanel>
<Rectangle>
<Rectangle.Fill>
<VisualBrush TileMode="FlipXY" Viewport="0,0,0.5,0.5"
Visual="{Binding ElementName=stackPanel}"/>
</Rectangle.Fill>
</Rectangle>
</DockPanel>
</Window>
.15.38 .
Visual VisualBrush StackPanel,
. VisualBrush
Rectangle, .
, , ,
.
, Button CheckBox,
.
, ,
!
. VisualBrush,
591
(,
) . Internet Explorer ( 7)
(Quick Tabs). , Windows
, VisualBrush,
,
,
Alt+Tab Windows+Tab.
VisualBrush
. TextBox
, ,
XAML:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TextBox with Reflection" Width="500" Height="200" Background="DarkGreen">
<StackPanel Margin="40">
<TextBox x:Name="textBox" FontSize="30"/>
<Rectangle Height="{Binding ElementName=textBox, Path=ActualHeight}"
Width="{Binding ElementName=textBox, Path=ActualWidth}">
<Rectangle.Fill>
<VisualBrush Visual="{Binding ElementName=textBox}"/>
</Rectangle.Fill>
<Rectangle.LayoutTransform>
<ScaleTransform ScaleY="-0.75"/>
</Rectangle.LayoutTransform>
</Rectangle>
</StackPanel>
</Window>
Rectangle, VisualBrush,
ScaleTransform.
ScaleY -1, -0.75,
. .15.39.
592
15.
.15.39.
,
. ,
, .
Visual ( DrawingGroup) Opacity,
. ,
, OpacityMask,
, . OpacityMask
, -
, ,
, ,
.
-, OpacityMask,
, DrawingBrush,
ImageBrush (, PNG-
) .. Window -
OpacityMask -
, .15.40:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="LinearGradientBrush OpacityMask">
<Window.Background>
<LinearGradientBrush>
<GradientStop Offset="0" Color="Orange"/>
<GradientStop Offset="1" Color="Brown"/>
</LinearGradientBrush>
</Window.Background>
<Button Margin="40" FontSize="80">OK
<Button.OpacityMask>
<LinearGradientBrush EndPoint="0.1,0.1" SpreadMethod="Reflect">
<GradientStop Offset="0" Color="Blue"/>
<GradientStop Offset="1" Color="Transparent"/>
</LinearGradientBrush>
</Button.OpacityMask>
</Button>
</Window>
593
.15.40. ,
LinearGradientBrush
- ,
,
, ,
. , .
.15.41 , , Opa
cityMask DrawingBrush,
.
. , Button
Geometry, .
,
. .
.15.41. DrawingBrush
OpacityMask;
( AllowsTransparency true ),
7 ,
OpacityMask !
594
15.
, , OpacityMask,
, .15.39:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TextBox with Reflection" Width="500" Height="200"
Background="DarkGreen">
<StackPanel Margin="40">
<TextBox x:Name="textBox" FontSize="30"/>
<Rectangle Height="{Binding ElementName=textBox, Path=ActualHeight}"
Width="{Binding ElementName=textBox, Path=ActualWidth}">
<Rectangle.Fill>
<VisualBrush Visual="{Binding ElementName=textBox}"/>
</Rectangle.Fill>
<Rectangle.LayoutTransform>
<ScaleTransform ScaleY="-0.75"/>
</Rectangle.LayoutTransform>
<Rectangle.OpacityMask>
<LinearGradientBrush EndPoint="0,1">
<GradientStop Offset="0" Color="Transparent"/>
<GradientStop Offset="1" Color="#77000000"/>
</LinearGradientBrush>
</Rectangle.OpacityMask>
</Rectangle>
</StackPanel>
</Window>
. 15.42 . ,
OpacityMask ,
.
.15.42. ,
WPF ,
Visual. System.Windows.Media.Ef
fects. DropShadowEffect BlurEffect,
595
Effect. .15.43
Button. WPF
.
(BlurEffect)
.15.43.
Visual
VisualEffect, (, UIElement)
Effect. ,
Effect Effect.
, .15.43 :
<Button Width="200">
DropShadowEffect
<Button.Effect>
<DropShadowEffect/>
</Button.Effect>
</Button>
BitmapEffect!
WPF ,
BitmapEffect. , Effect,
BitmapEffect,
BitmapEffect. ,
.
Effect BitmapEffect ,
Effect , Bitmap
Effect .
, BitmapEffect,
BlurEffect DropShadowEffect . ,
BitmapEffect BevelBitmapEffect, EmbossBitmapEffect Outer
GlowBitmapEffect .
, BitmapEffect ,
WPF. , , ,
. , ,
, , .
.
596
15.
.15.43
.
.
.15.3.
WPF
, ShaderEffect, Effect,
. (
, BitmapEffect,
C++ COM.)
ShaderEffect,
, Effect.
DirectX,
, High Level Shader
Language (HLSL).
, ShaderEffect,
WPF Pixel Shader Effects Library http://wpffx.codeplex.
com. , :
BandedSwirlEffect
BloomEffect
BrightExtractEffect
ColorKeyAlphaEffect
ColorToneEffect
ContrastAdjustEffect
DirectionalBlurEffect
EmbossedEffect
GloomEffect
GrowablePoissonDiskEffect
InvertColorEffect
LightStreakEffect
MagnifyEffect
MonochromeEffect
PinchEffect
PixelateEffect
RippleEffect
SharpenEffect
SmoothMagnifyEffect
SwirlEffect
ToneEffect
ToonEffect
ZoomBlurEffect
:
BandedSwirlTransitionEffect
BlindsTransitionEffect
BloodTransitionEffect
CircleRevealTransitionEffect
CircleStretchTransitionEffect
CircularBlurTransitionEffect
CloudReveralTransitionEffect
CloudyTransitionEffect
CrumbleTransitionEffect
DissolveTransitionEffect
DropFadeTransitionEffect
FadeTransitionEffect
LeastBrightTransitionEffect
LineRevealTransitionEffect
MostBrightTransitionEffect
PixelateInTransitionEffect
PixelateOutTransitionEffect
PixelateTransitionEffect
RadialBlurTransitionEffect
RadialWiggleTransitionEffect
RandomCircleRevealTransitionEffect
RippleTransitionEffect
RotateTransitionEffect
SaturateTransitionEffect
ShrinkTransitionEffect
SlideInTransitionEffect
SmoothSwirlTransitionEffect
SwirlTransitionEffect
WaterTransitionEffect
WaveTransitionEffect
597
15.3.
DropShadowEffect
RenderingBias ( Performance
): Performance (
) Quality ()
BlurRadius ( ): 5
double
Color: ( Black
-)
Direction: double, 315
Opacity: double 0 ( 1
) 1 ( )
ShadowDepth ( ): 5
double
BlurEffect
Performance
Radius: double 5
KernelType ( ): Box Gaussian Gaussian
,
.
( DrawingContext,
Visual),
.
,
,
.
.
WPF . Ren
derTargetBitmap, WPF. Bitmap
Cache BitmapCacheBrush
.
, WPF4.
RenderTargetBitmap
RenderTargetBitmap, BitmapSource (,
, ImageSource), Visual
598
15.
, Visual.
, Visual.
RenderTargetBitmap,
Visual:
private static ImageSource ProduceImageSourceForVisual(
Visual source, double dpiX, double dpiY)
{
if (source == null)
return null;
Rect bounds = VisualTreeHelper.GetDescendantBounds(source);
RenderTargetBitmap bitmap = new RenderTargetBitmap(
(int)(bounds.Width * dpiX / 96), (int)(bounds.Height * dpiY / 96),
dpiX, dpiY, PixelFormats.Pbgra32);
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext ctx = drawingVisual.RenderOpen())
{
ctx.DrawRectangle(new VisualBrush(source), null,
new Rect(new Point(), bounds.Size));
}
bitmap.Render(drawingVisual);
return bitmap;
}
Visual VisualBrush ,
. Visual
,
.
BitmapCache
RenderTargetBitmap ,
:
WPF4
, , RenderTargetBitmap!
BitmapCache UIEle
ment
.
XAML-. ,
RenderTargetBitmap,
.
599
,
CacheMode UIElement, .
CacheMode CacheMode,
WPF BitmapCache.
, Grid :
<Grid ...>
<Grid.CacheMode>
<BitmapCache/>
</Grid.CacheMode>
...
</Grid>
( ) , Bit
mapCache .
,
, ! , WPF
,
.
BitmapCache :
RenderAtScale double, 1. ,
.
, .
, ,
, .
RenderAtScale , 1,
.
SnapsToDevicePixels ; true,
.
EnableClearType ; true,
ClearType .
true, true
SnapsToDevicePixels, .
.
.15.44 RenderAtScale
, XAML-:
<Button>
<Button.CacheMode>
<BitmapCache RenderAtScale="..."/>
</Button.CacheMode>
...
</Button>
, Button,
, Button
RenderAtScale .
600
15.
BitmapCache ,
.
20482048
.
RenderAtScale=1
RenderAtScale=0.5
RenderAtScale=0.1
RenderAtScale=0.01
.15.44. RenderAtScale
BitmapCache ,
,
WPF - ,
.
. ,
.
601
BitmapCacheBrush
BitmapCacheBrush
, .
Target BitmapCacheBrush
Visual BitmapCacheBrush ,
Visual CacheMode. , CacheMode
,
BitmapCacheBrush. ( BitmapCacheBrush CacheMode,
BitmapCache BitmapCache, .)
, BitmapCacheBrush Visual
Brush.
,
.
BitmapCacheBrush !
BitmapCacheBrush SnapsToDevicePixels,
, false. EnableClearType
true BitmapCache, BitmapCacheBrush,
CacheMode Visual, Target
BitmapCacheBrush.
,
, . ,
, ,
WPF. Windows, WPF
DirectX ,
.
,
,
. ;
18.
WPF,
. ,
,
, . ,
WPF .
Transform3D
Model3D
Visual3D
Viewport3D
16
16.
603
, ,
.
. -,
, . -,
API, WPF. -,
,
, DirectX,
, WPF.
,
, . 3D-
, , ,
.
, ,
.
(50,75) 100 30 , , ,
Rectangle ( GeometryDrawing Rec
tangleGeometry ). 16.1,
Drawing .
.16.1.
16.1. Drawing
<Page Background="Black"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Image>
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<DrawingGroup x:Name="House">
<GeometryDrawing x:Name="Front" Brush="Red"
Geometry="M0,260 L0,600 L110,670 L110,500 L190,550
L190,710 L300,775 L300,430 L150,175"/>
<GeometryDrawing x:Name="Side" Brush="Green"
Geometry="M300,430 L300,775 L600,600 L600,260"/>
<GeometryDrawing x:Name="Roof" Brush="Blue"
Geometry="M150,175 L300,430 L600,260 L450,0"/>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
</Page>
604
16.
.16.1. , Drawing
, ,
, .
.
, ,
, .
, .
(
),
.
16.2 ,
, Model3D Drawing.
16.2 ,
. 3D-,
, ;
.16.2 .
16.2. , 3D-
<Page Background="Black"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Viewport3D>
<Viewport3D.Camera>
<OrthographicCamera Position="5,5,5" LookDirection="-1,-1,-1" Width="5"/>
</Viewport3D.Camera>
<Viewport3D.Children>
<ModelVisual3D x:Name="Light">
<ModelVisual3D.Content>
<AmbientLight/>
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D>
<ModelVisual3D.Content>
<Model3DGroup x:Name="House">
<GeometryModel3D x:Name="Roof">
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Blue"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="-1,1,1 0,2,1 0,2,-1 -1,1,
-1 0,2,1 1,1,1 1,1,-1 0,2,-1"
TriangleIndices="0 1 2 0 2 3 4 5 6 4 6 7"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
<GeometryModel3D x:Name="Sides">
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Green"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="-1,1,1 -1,1,-1 -1,-1,
-1 -1,-1,1 1,1,-1 1,1,1 1,-1,1 1,-1,-1"
TriangleIndices="0 1 2 0 2 3 4 5 6 4 6 7"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
<GeometryModel3D x:Name="Ends">
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Red"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D
Positions="-0.25,0,1 -1,1,1 -1,-1,1 -0.25,-1,1 -0.25,0,1
-1,-1,1 0.25,0,1 1,-1,1 1,1,1 0.25,0,1 0.25,-1,
1 1,-1,1 1,1,1 0,2,1 -1, 1,1 -1,1,1 -0.25,0,
1 0.25,0,1 1,1,1 1,1,-1 1,-1,-1 -1,-1,-1 -1,
1,-1 1,1,-1 -1,1,-1 0,2,-1"
TriangleIndices="0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
15 17 18 19 20 21 19 21 22 23 24 25"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
</Model3DGroup>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D.Children>
</Viewport3D>
</Page>
605
606
16.
.16.2.
16.2 ,
. ,
, 15 . .16.1
.
16.1.
Drawing
Model3D
Drawing
, ,
Visual.
Model3D
,
Visual3D.
Geometry
Geometry3D
Geometry
.
,
.
Geometry .
Geom etryDrawing Geo
metry Brush
.
Geometry3D
. Geomet
ry3D,
Material GeometryModel3D.
Visual
Visual3D
Visual ,
.
DrawingVisual ,
FrameworkElement, Control
Shape.
Visual3D ,
. Model
Visual3D Visual3D,
,
Model3D.
607
UIElement
UIElement3D
UIElement Visual,
,
WPF
. , UIElement
1 (LIFE layout, input, focus, even
ting , , , )
.
UIElement3D UIEle
ment, IFE (input, focus, eventing
, , ) 3D.
,
.
Transform
Transform3D
Transform
,
Drawing Visual.
16.2 Transform3D,
, ,
Model3D Visual3D.
3D- API,
, ; 16.2
:1
Camera 3D-
. ,
, .
Material Light
. ,
.
, ,
3D-.
, ,
, .. WPF ,
Viewport3D, 3D-
1
: LIFE life . . .
608
16.
( Camera).
(
). .16.3
, WPF.
2D
3D
.16.3.
z
.
y , . ,
,
, 3D.
, . ,
,
.
Camera OrthographicCamera Per
spectiveCamera
.
, ,
3D- .
Position
Position .
, . Position Point3D.
Point3D x, y, z
. 16.2
(5,5,5):
<Viewport3D.Camera>
<OrthographicCamera Position="5,5,5" LookDirection="-1,-1,-1" Width="5"/>
</Viewport3D.Camera>
609
WPF
z xy. x y
, .16.4, z
. z
, .
z , .
.16.4.
WPF .
:
x,
y,
z (.16.5).
.16.5.
, .
MeshGeometry3D.
610
16.
,
x, y z.
.16.6 , -
. (
,
.)
.16.6. ,
-
- ,
(-5,5,5):
<Viewport3D.Camera>
<OrthographicCamera Position="-5,5,5" LookDirection="-1,-1,-1" Width="5"/>
</Viewport3D.Camera>
.16.7.
.16.7. ,
-
,
. ,
611
, ,
10 . ,
. LookDirection ,
.
LookDirection
LookDirection , .
Vector3D. Point3D, Vector3D
x, y, z, ,
. Vector3D
Length :
x2 + y2 + z2 .
!
, , NearPlaneDis
tance, . Position
,
, NearPlaneDistance, . .16.8
, , .
NearPlaneDistance Camera ,
Z-
. Z- , ,
Z- (Z-fighting),
, . .16.9
,
. .
Z-
, . NearPlaneDistance
Camera Z-,
, . NearPlaneDistance
0.125, .
, ,
Z-. ,
. FarPlaneDistance,
, ,
.
, Z- ,
, , .
, , , .
,
. ,
, .
612
16.
.16.8. -
.16.9.
Z-
x, y, z , ,
-, .16.10.
, (-5,5,5),
. . 16.11 .
LookDirection,
.
.16.10.
-
.16.11.
613
LookDirection , - , ,
Position Camera.
(0,0,0). (-5,5,5)
(0,0,0) <5,-5,-5>, .16.12.
.16.12.
LookDirection ,
.16.13:
<Viewport3D.Camera>
<OrthographicCamera Position="-5,5,5" LookDirection="5,-5,-5" Width="5"/>
</Viewport3D.Camera>
.16.13.
614
16.
, Vector3D ,
, .
LookDirection <1,-1,-1>, ,
.16.13.
, WPF .
, Vector3D
- ( <0,0,0>),
Point3D.
Vector3D Point3D,
Point3D, (Length) ,
. ,
. , Vec
tor3DAnimation .
,
, LookDirection
, :
private void LookAt(ProjectionCamera camera, Point3D lookAtPoint)
{
camera.LookDirection = lookAtPoint - camera.Position;
}
UpDirection
LookDirection , ,
.
, .16.14.
.
,
UpDirection ( ).
.16.14. UpDirection
615
UpDirection <0,1,0>. ,
<1,0,0>, , , . .16.15
, UpDirection.
<Viewport3D.Camera>
<OrthographicCamera Position="5,5,5" LookDirection="-1,-1,-1"
UpDirection="1,0,0" Width="5"/>
</Viewport3D.Camera>
.16.15.
x UpDirection
Position, UpDirection LookDirection.
, ,
,
Camera.Transform.
Camera.Transform , ,
, ,
Transform3D.
Camera.Transform ,
,
3D- . ,
Transform3D.
616
16.
UpDirection!
180, , ,
, UpDirection. ,
LookDirection UpDirection,
.16.16.
, LookDirection
, .
, , .
UpDirection -
y,
. , ,
, LookDirection UpDirection
.
UpDirection LookDirection, .16.17.
.16.16.
617
.16.17.
OrthographicCamera PerspectiveCamera
WPF , .
PerspectiveCamera ,
, , ,
, .
. , OrthographicCamera,
,
,
.
. .16.18
,
.
3D- , ,
.
, ,
.16.19.
618
16.
.
OrthographicCamera.Width.
Viewport3D , 1:1.
:
<Viewport3D.Camera>
<OrthographicCamera Position="5,5,5" LookDirection="-1,-1,-1" Width="5"/>
</Viewport3D.Camera>
.16.18.
.16.19.
619
.
,
. ,
.16.20.
,
.
FieldOfView. WPF
. :
<Viewport3D.Camera>
<PerspectiveCamera Position="5,5,5" LookDirection="-1,-1,-1" FieldOfView="45""/>
</Viewport3D.Camera>
FieldOfView
.
Width. Width FieldOfView,
3D- . Width FieldOfView,
.
.16.20.
620
16.
MatrixCamera
WPF , MatrixCamera,
Matrix3D.
,
.
MatrixCamera , ,
Direct3D. MatrixCamera
, WPF ,
.
, MatrixCamera, Direct3D.
, D3DX.
DirectX SDK.
Transform3D
Transform , Transform3D
, 3D-.
Transform3D Model3D, ModelVisual3D Camera.
Transform.
Transform 3D-
. ,
,
Canvas.Left Canvas.Top.
.16.21 15.
. TranslateTransform
,
. .16.21.
TranslateTransform
Visual , .
,
. Canvas
TranslateTransform
Visual.
. 3D-
.
, 3D-
, Transform3D:
TranslateTransform3D 3D-
.
621
Transform3D
.16.21.
ScaleTransform3D 3D-
.
RotateTransform3D 3D- .
MatrixTransform3D 3D-, Mat
rix3D.
Transform3DGroup Transform3D. Trans
form3DGroup Transform3D
3D-.
,
. 16.3 XAML-,
, . -,
( , ), -,
Width ,
.
16.3.
<Page Background="Black"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Viewport3D>
<Viewport3D.Camera>
<OrthographicCamera Position="5,5,5" LookDirection="-1,-1,-1" Width="10"/>
</Viewport3D.Camera>
<Viewport3D.Children>
<ModelVisual3D x:Name="Light">
<ModelVisual3D.Content>
<AmbientLight/>
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D>
<ModelVisual3D.Transform>
622
16.
<x:Static Member="Transform3D.Identity"/>
</ModelVisual3D.Transform>
<ModelVisual3D.Content>
<Model3DGroup x:Name="House">
<GeometryModel3D x:Name="Roof">
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Blue"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="-1,1,1 0,2,1 0,2,-1 -1,1,
-1 0,2,1 1,1,1 1,1,-1 0,2,-1"
TriangleIndices="0 1 2 0 2 3 4 5 6 4 6 7"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
<GeometryModel3D x:Name="Sides">
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Green"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="-1,1,1 -1,1,-1 -1,-1,
-1 -1,-1,1 1,1,-1 1,1,1 1,-1,1 1,-1,-1"
TriangleIndices="0 1 2 0 2 3 4 5 6 4 6 7"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
<GeometryModel3D x:Name="Ends">
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Red"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D
Positions="-0.25,0,1 -1,1,1 -1,-1,1 -0.25,-1,
1 -0.25,0,1 -1,-1,1 0.25,0,1 1,-1,1 1,1,
1 0.25,0,1 0.25,-1,1 1,-1,1 1,1,1 0,2,1 -1,
1,1 -1,1,1 -0.25,0,1 0.25,0,1 1,1,1 1,1,
-1 1,-1,-1 -1,-1,-1 -1,1,-1 1,1,-1 -1,1,
-1 0,2,-1"
TriangleIndices="0 1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 15 17 18 19 20 21 19 21 22 23 24 25"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
</Model3DGroup>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D.Children>
</Viewport3D>
</Page>
Transform3D
623
TranslateTransform3D
TranslateTransform3D
. OffsetX, OffsetY
OffsetZ. , OffsetZ = 3,
z , .16.22:
<ModelVisual3D.Transform>
<TranslateTransform3D OffsetZ="3"/>
</ModelVisual3D.Transform>
.16.22. z
, 3D-
, . ,
.
(3,2,1),
:
<ModelVisual3D.Transform>
<TranslateTransform3D OffsetX="3" OffsetY="2" OffsetZ="1"/>
</ModelVisual3D.Transform>
ScaleTransform3D
ScaleTransform3D ,
3D-.
ScaleX, ScaleY ScaleZ.
, ScaleTransform3D
. ,
x (.16.23):
<ModelVisual3D.Transform>
<ScaleTransform3D ScaleX="2"/>
</ModelVisual3D.Transform>
624
16.
.16.23. x
3D- , Sca
leX, ScaleY ScaleZ .
. 2,
, 0.5 .
, 1, 0!
,
1:1, 1:0. ScaleX, ScaleY ScaleZ, 0,
.
,
.
, !
, .
, .
. .16.23
, .
, (3,0,0),
0.5,
(1.5,0,0),
. XAML-
.16.24:
<ModelVisual3D.Transform>
<Transform3DGroup>
<TranslateTransform3D OffsetX="3"/>
<ScaleTransform3D ScaleX="0.5" ScaleY="0.5" ScaleZ="0.5"/>
</Transform3DGroup>
</ModelVisual3D.Transform>
Transform3D
625
.16.24. ,
,
. CenterX, CenterY CenterZ.
XAML- .
<ModelVisual3D.Transform>
<Transform3DGroup>
<TranslateTransform3D OffsetX="3"/>
<ScaleTransform3D ScaleX="0.5" ScaleY="0.5" ScaleZ="0.5" CenterX="3"/>
</Transform3DGroup>
</ModelVisual3D.Transform>
, .16.25.
.16.25.
626
16.
<ModelVisual3D.Transform>
<Transform3DGroup>
<ScaleTransform3D ScaleX="0.5" ScaleY="0.5" ScaleZ="0.5"/>
<TranslateTransform3D OffsetX="3"/>
</Transform3DGroup>
</ModelVisual3D.Transform>
, ,
, , .
,
x.
.16.24, , , ,
. ,
.
. .16.26 ,
ScaleZ
xy:
<ModelVisual3D.Transform>
<Transform3DGroup>
<TranslateTransform3D OffsetZ="3"/>
<ScaleTransform3D ScaleZ="-1"/>
</Transform3DGroup>
</ModelVisual3D.Transform>
.16.26. z
, z.
, OffsetZ
.
Transform3D
627
CenterX, CenterY CenterZ
,
.
, .
, x, y, z. Rotati
onTransform3D ,
.
,
, .
RotateTransform3D
RotateTransform3D 3D-
. Rotation3D.
:
AxisAngleRotation3D Axis Angle,
.
.
QuaternionRotation3D Quaternion.
,
.
FAQ
WPF -
?
WPF ,
,
. 0 360,
Rotation3DAnimation
,
. , 179,9999,
,
.
Axis/Angle, 3D-
.
Angle DoubleAnimation.
628
16.
Quaternion ,
,
.
,
Axis/Angle,
, AxisAngleRotation3D QuaternionRotation3D
Rotation3D.
Rotation3D Rotation3DAnimation,
.
WPF ,
.
. ,
, .
WPF EulerAngleRotation3D,
Transform3D, Transform3DGroup
RotateTransform3D, XAML-:
<Transform3DGroup>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D x:Name="RotateX" Axis="1,0,0" Angle="0"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D x:Name="RotateY" Axis="0,1,0" Angle="0"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D x:Name="RotateZ" Axis="0,0,1" Angle="0"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
</Transform3DGroup>
, , ,
.
.16.27 45 y:
<ModelVisual3D.Transform>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D Axis="0,1,0" Angle="45"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
</ModelVisual3D.Transform>
Transform3D
629
.16.27. 45 y
, x z .
, ,
, ScaleTransform3D:
<ModelVisual3D.Transform>
<Transform3DGroup>
<TranslateTransform3D OffsetZ="3"/>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D Axis="0,1,0" Angle="45"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
</Transform3DGroup>
</ModelVisual3D.Transform>
. .
, ,
.16.28.
.16.28.
630
16.
, ,
CenterX, CenterY CenterZ:
<ModelVisual3D.Transform>
<Transform3DGroup>
<TranslateTransform3D OffsetZ="3"/>
<RotateTransform3D CenterZ="3">
<RotateTransform3D.Rotation>
<AxisAngleRotation3D Axis="0,1,0" Angle="45"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
</Transform3DGroup>
</ModelVisual3D.Transform>
. ,
.
<ModelVisual3D.Transform>
<Transform3DGroup>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D Axis="0,1,0" Angle="45"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
<TranslateTransform3D OffsetZ="3"/>
</Transform3DGroup>
</ModelVisual3D.Transform>
Transform3D
,
, 3D-
: , ( ,
).
Transform3DGroup. XAML-
Transform3DGroup:
<Transform3DGroup>
<ScaleTransform3D x:Name="Size" ScaleX="1" ScaleY="1" ScaleZ="1"/>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D x:Name="Orientation" Axis="0,1,0" Angle="0"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
<TranslateTransform3D x:Name="Position" OffsetX="0" OffsetY="0" OffsetZ="0"/>
</Transform3DGroup>
Model3D
631
MatrixTransform3D
WPF Transform3D: MatrixTrans
form3D.
Matrix3D. ,
, Matrix3D 44. ,
, , .
MatrixTransform3D ,
Transform3D, ,
.
, Transform3D
Matrix3D Value.
Transform3DGroup, ,
Transform3D MatrixTransform3D.
Model3D
Model3D ,
. Model3D Drawing .
Drawing
WPF-
, Model3D 3D- WPF.
WPF Model3D:
Light , .
, Light Model3D,
, ,
Model3DGroup.
XAML-
, 3D-
.
,
. , ,
.
, ,
3D-,
XAML.
, .
3D-, ZAM 3D Electric Rain,
WPF XAML.
632
16.
GeometryModel3D (
Light
, WPF
. , ,
Brush Pen. 3D
,
.
.
: Light,
; Material, , -
; (Geometry) ,
.
, WPF:
DirectionalLight ( )
, .
, .
PointLight ( )
. .
PointLight ,
.
SpotLight () . PointLight,
. SpotLight
, .
AmbientLight ( ) .
-
.
,
.
, ,
. ,
, WPF, ,
.
,
.
Model3D
633
: (
); ,
. WPF
.
.
,
, ,
.. - .
API
, .
DirectionalLight
DirectionalLight ,
, .
, , . .16.29
, :
<DirectionalLight Direction="1,-1,-0.5" Color="White"/>
, , Direction.
, Transform, Model3D,
. Color.
.16.29. DirectionalLight,
DirectionalLight
. ,
634
16.
( ),
, .
, , AmbientLight,
.
Color . ,
#FFFFFF . #808080
. - .
. , (
Position, Direction ..)
, .
PointLight
PointLight ,
, , ,
. DirectionalLight, ,
PointLight, .
. 16.30
PointLight, :
<PointLight Color="White" Position="2,2,2"
ConstantAttenuation="0"
LinearAttenuation="0"
QuadraticAttenuation="0.125"/>
PointLight Position.
, ConstantAttenuation (
), LinearAttenuation ( ) QuadraticAttenuation (
):
=
1
max(1, C + Ld + Qd2)
Model3D
635
. Range
.
.16.30. PointLight,
SpotLight
SpotLight (PointLight), .
.
. .16.31 , SpotLight
PointLight,
.
.16.31. SpotLight,
636
16.
FAQ
SpotLight PointLight
?
,
. , WPF
.
,
PointLight SpotLight.
.16.32. , .
SpotLight ,
PointLight Range. ,
, .
,
, . 16.33.
, ,
SpotLight .
, .
,
.
,
.16.31, .
, ,
, .
, .
.16.32.
.16.33.
Model3D
637
Direction .
OuterConeAngle InnerConeAngle. :
<SpotLight Color="White" Position="2,2,2"
Direction="-1,-1,-1"
InnerConeAngle="45"
OuterConeAngle="90"/>
InnerConeAngle
, Color. InnerConeAngle Outer
ConeAngle . Inner
ConeAngle OuterConeAngle, .
InnerConeAngle OuterConeAngle,
SpotLight, .
AmbientLight
AmbientLight ,
,
. AmbientLight
, .16.34.
AmbientLight , Color,
. Transform,
Model3D, AmbientLight .
.16.34. AmbientLight,
638
16.
AmbientLight (.
) ,
.16.35:
<AmbientLight Color="White"/>
.16.35. AmbientLight
AmbientLight
, ,
. .16.36
AmbientLight :
<Model3DGroup>
<DirectionalLight Direction="1,-1,-1" Color="White"/>
<AmbientLight Color="#FF333333"/>
</Model3DGroup>
,
: AmbientLight
( #555555 ).
, AmbientLight
, DiffuseMaterial.AmbientColor. ,
AmbientColor, ,
DiffuseMaterial, Ambi
entLight.
639
Model3D
DirectionalLight
AmbientLight
.16.36. AmbientLight
GeometryModel3D
, 3D-, . WPF
Geometry3D.
Geometry3D
.
, Material. GeometryMo
del3D, Model3D,
Geometry Material.
GeometryModel3D,
( MeshGeometry3D) DiffuseMaterial:
<GeometryModel3D>
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Blue"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0 1,1,0"
TriangleIndices="0 1 2, 0 2 3"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
,
MeshGeometry3D.
Material
, Light
, . ,
,
640
16.
.
. ,
.
WPF Material ,
.
, WPF:
DiffuseMaterial ( )
, ,
.
SpecularMaterial ( ) ,
.
,
.
EmissiveMaterial ( ) ,
. ,
;
.
. ,
,
, , ,
.
MaterialGroup .
,
.
DiffuseMaterial. . ,
, ,
, .
.16.37 .
.16.37. (. )
641
Model3D
.
,
.16.38. , ,
.
. ,
, ,
.
.16.38.
, , Brush.
.16.37
, .
<DiffuseMaterial Brush="Red"/>
, ,
, . ,
.16.39 ,
ImageBrush:
<DiffuseMaterial>
<DiffuseMaterial.Brush>
<ImageBrush ImageSource="C:\ZebraStripes.png" ViewportUnits="Absolute"/>
</DiffuseMaterial.Brush>
</DiffuseMaterial>
, SolidColorBrush,
!
GradientBrush, ImageBrush, DrawingBrush
VisualBrush, ,
.
, .
SolidColorBrush ,
.
. SolidColorBrush , ,
, , .
642
16.
ImageBrush
ImageBrush
.16.39. ImageBrush,
(. )
WPF ,
.
3D-, ,
Drawing,
, DocumentViewer!
,
( UV-)
Geometry. .
.16.39 ImageBrush ,
, , .
.
, ImageBrush.
Color .
.
, .
Color . ,
,
, .
643
Model3D
, , :
n
Lci Mci
Mb
i=0
Lc Color , Mc Color
, Mb . -
Color . -
.
Color
.
, ,
..
Color , ,
. , ,
, .
ImageSource, ;
.16.39 ,
:
<DiffuseMaterial Color="Orange">
<DiffuseMaterial.Brush>
<ImageBrush ImageSource="C:\ZebraStripes.png" ViewportUnits="Absolute"/>
</DiffuseMaterial.Brush>
</DiffuseMaterial>
, ,
3D-,
.
FAQ
?
:
ImageSource -,
Brush.Opacity - DiffuseMaterial.
Color. ,
, .
644
16.
, WPF .
, , ,
( ), WPF
, ,
. ,
(
), :
, , ,
. , .
,
, .
, 3D-
, Children.
Children, ,
.
EmissiveMaterial. ,
.
.
FAQ
WPF AmbientMaterial?
, ,
, Di
rect3D 3D-, , , WPF
AmbientMaterial.
(ambient), , ,
.
, ,
AmbientLight
. , ,
AmbientLight,
.
AmbientLight.
WPF AmbientColor DiffuseMaterial.
Color ,
, AmbientLight. AmbientColor
AmbientLight.
, ,
Color DiffuseMaterial,
SpecularMaterial EmissiveMaterial .
AmbientColor DiffuseMaterial.
645
Model3D
EmissiveMaterial. ,
.
. .16.40
:
<EmissiveMaterial Brush="Green"/>
.
,
, , .
. 16.40
. -
, - ( ,
).
, Emis
siveMaterial DiffuseMaterial, MaterialGroup:
<MaterialGroup>
<DiffuseMaterial Brush="Black"/>
<EmissiveMaterial Brush="Green"/>
</MaterialGroup>
.16.40.
EmissiveMaterial
EmissiveMaterial DiffuseMaterial
.16.40. (. )
, ,
. , ,
,
. ,
. ,
646
16.
,
.
SpecularMaterial.
, ,
.
, , .16.41:
<SpecularMaterial Brush="White" SpecularPower="10"/>
SpecularMaterial DiffuseMaterial,
( .16.41):
<MaterialGroup>
<DiffuseMaterial Brush="Red"/>
<SpecularMaterial Brush="White" SpecularPower="40"/>
</MaterialGroup>
.16.37.
SpecularPower.
, .
SpecularMaterial
SpecularMaterial DiffuseMaterial
.16.41. (. )
,
.
.
Model3D
647
, ,
,
. .16.42, Specular
Material, , ,
.
.16.42.
, , AmbientLight ,
.
, ,
, Color
Brush SpecularMaterial Color .
Diffuse
Material .
,
, WPF
Brush. -
, ,
. , (gloss
mapping),
, ..
. ,
MaterialGroup .
EmissiveMaterial SpecularMaterial DiffuseMa
terial, .
Geometry3D
Geometry Geometry3D
. Geometry3D
. Model3D,
, ,
GeometryModel3D. Geometry3D
: MeshGeometry3D.
648
16.
MeshGeometry3D ,
. :
Positions , (
).
TriangleIndices , .
TriangleIndices , ,
0 1 2, 3 4 5 ..
Normals .
TextureCoordinates
, .
Positions, Normals TextureCoordinates ,
. ,
0 Positions,
0 Normals ..
Positions. , ,
.
Positions MeshGeometry3D.
Point3D Positions . ,
, .16.43.
<MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0"/>
, (.16.44).
<MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0 -1,1,0 1,-1,0 1,1,0"/>
.16.43. ,
MeshGeometry3D
.16.44. ,
MeshGeometry3D
. ,
, ,
, MeshGeometry3D
.
. - ,
Material null. ,
649
Model3D
. .16.45
, , .
.
, 0 1, ,
0 1.
, ,
.16.45.
.16.45.
, z .
, ,
. , ,
, . .16.46,
.
.16.46.
.
650
16.
, - ,
Material BackMaterial ,
, .
,
.
. ,
, BackMaterial,
.
TriangleIndices.
.
.
.
TriangleIndices
. TriangleIndices , ,
,
Positions. ,
TriangleIndices. , , . 16.47,
, :
<MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0 1,1,0"
TriangleIndices="0 1 2, 0 2 3"/>
. ,
.
,
,
.
.16.47.
651
Model3D
, TriangleIndices ,
,
MeshGeometry3D, . WPF
, ,
, .
, .
MeshGeometry3D ,
, , -
.
,
.
MeshGeometry3D , ,
.
Normals. ,
. ,
, ,
. .16.48
, 12
.
.16.48. , 12
,
.16.49,
652
16.
. ,
.
, .16.49,
.
.16.49. , .16.48
, ,
, .
,
, ,
.16.48. TriangleIndices ,
,
, .16.48 .
, . ,
,
, .16.50 :
<MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0 1,1,0"
TriangleIndices="0 1 2, 0 2 3"
Normals="0,0,1 0,0,1 0,0,1 0,0,1"/>
, ,
,
, .16.50 :
<MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0 1,1,0"
TriangleIndices="0 1 2, 0 2 3"
Normals="-0.25,0.25,1 -0.25,-0.25,1 0.25,-0.25,1 0.25,0.25,1"/>
653
Model3D
.16.50.
TextureCoordinates. Fill
Shape ,
, .
. TextureCoordina
tes .
.
. . 16.51 ,
, :
<MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0 1,1,0"
TriangleIndices="0 1 2, 0 2 3"
TextureCoordinates="0,0 0,1 1,1 1,0"/>
, WPF ,
, y
. , -
(0,0) (1,1).
.16.51.
654
16.
WPF ,
, , !
WPF.
, 2D3D-.
, ,
.
-, ,
. ,
, , , :
<MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0 1,1,0"
TriangleIndices="0 1 2, 0 2 3"
TextureCoordinates="0,0 0,0.5 0.5,0.5 0.5,0"/>
(0,0) (0.5,0.5)
.
, ViewportUnits Absolute:
<ImageBrush ViewportUnits="Absolute" .../>
.
. .
-, ,
y , , WPF.
, ,
, .
:
<ImageBrush ViewportUnits="Absolute" Transform="1,0,0,-1,0,1" .../>
,
0 1, , , .
WPF TileMode :
<ImageBrush ViewportUnits="Absolute" Transform="1,0,0,-1,0,1" TileMode="Tile" .../>
ImageBrush,
, .
Model3DGroup
Model3DGroup Model3D.
Model3D .
GeometryModel3D Model3DGroup ,
. 16.4 ,
GeometryModel3D .
Model3D
655
MeshGeometry3D,
MaterialGroup.
(mesh) ,
, .
. WPF
Model3DGroup, Geomet
ryModel3D, .
16.4.
<Model3DGroup x:Name="Cube">
<GeometryModel3D x:Name="Front">
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Orange"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="1,1,1 -1,1,1 -1,-1,1 1,-1,1"
TextureCoordinates="1,1 0,1 0,0 1,0"
TriangleIndices="0 1 2 0 2 3"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
<GeometryModel3D x:Name="Right">
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Yellow"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="1,1,-1 -1,1,-1 -1,1,1 1,1,1"
TextureCoordinates="0,0 1,0 1,1 0,1"
TriangleIndices="0 1 2 0 2 3"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
<GeometryModel3D x:Name="Back">
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Red"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="-1,-1,-1 -1,1,-1 1,1,-1 1,-1,-1"
TextureCoordinates="1,0 1,1 0,1 0,0"
TriangleIndices="0 1 2 0 2 3"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
<GeometryModel3D x:Name="Left">
<GeometryModel3D.Material>
656
16.
<DiffuseMaterial Brush="Blue"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="-1,1,1 -1,1,-1 -1,-1,-1 -1,-1,1"
TextureCoordinates="1,1 0,1 0,0 1,0"
TriangleIndices="0 1 2 0 2 3"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
<GeometryModel3D x:Name="Top">
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Green"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="1,-1,1 1,-1,-1 1,1,-1 1,1,1"
TextureCoordinates="1,1 0,1 0,0 1,0"
TriangleIndices="0 1 2 0 2 3"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
<GeometryModel3D x:Name="Bottom">
<GeometryModel3D.Material>
<DiffuseMaterial Brush="Purple"/>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="-1,-1,1 -1,-1,-1 1,-1,-1 1,-1,1"
TextureCoordinates="0,1 0,0 1,0 1,1"
TriangleIndices="0 1 2 0 2 3"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
</Model3DGroup>
Visual3D
, ,
Visual.
Visual3D ,
. Visual ,
Visual3D
VisualTreeHelper.
WPF Visual3D: ModelVisual3D,
UIElement3D Viewport2DVisual3D. .
ModelVisual3D
ModelVisual3D DrawingVisual
WPF . ModelVisual3D
Content:
Visual3D
657
<Viewport3D>
<Viewport3D.Camera>
<OrthographicCamera Position="5,5,5" LookDirection="-1,-1,-1" Width="5"/>
</Viewport3D.Camera>
<Viewport3D.Children>
<ModelVisual3D Content="{StaticResource CubeModel}"/>
</Viewport3D.Children>
</Viewport3D>
FAQ
Model3DGroup,
ModelVisual3D?
, , Model3DGroup,
ModelVisual3D ( ModelUIElement3D,
),
. ModelVisual3D ModelUIElement3D
.
, Model3DGroup .
ModelVisual3D
GeometryModel3D . ,
.
Model3DGroup ,
GeometryModel3D .
Model3DGroup
(, ,
), ModelVisual3D ( ModelUIElement3D)
3D- (, ).
658
16.
UIElement3D
WPF3.5 UIElement3D
Visual3D
WPF 3D.
, WPF UIElement ,
LIFE (, , ).
, IFE (, ) UIElement3D
. ,
3D- .
Viewport3D,
, 3D- ,
UIElement3D.
WPF , UIElement3D: ModelUIElement3D
ContainerUIElement3D.
FooBar, , , ModelUIEle
ment3D UIElement3D, Model, ContainerUIElement3D UIEle
ment3D, .
ModelUIElement3D
16.5 16.6 ModelUIElement3D
, . ModelUI
Element3D Model3D, .
, MouseDown ModelUIEle
ment3D, Viewport3D.
16.5. MainWindow.xaml ,
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Viewport3D>
<Viewport3D.Camera>
<PerspectiveCamera Position="3,3,4" LookDirection="-1,-1,-1"
FieldOfView="60"/>
</Viewport3D.Camera>
<Viewport3D.Children>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight Direction="-0.3,-0.4,-0.5" />
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelUIElement3D MouseDown="Cube_MouseDown">
Visual3D
659
<ModelUIElement3D.Model>
<GeometryModel3D>
<GeometryModel3D.Material>
<DiffuseMaterial>
<DiffuseMaterial.Brush>
<SolidColorBrush Color="Purple" x:Name="CubeBrush"/>
</DiffuseMaterial.Brush>
</DiffuseMaterial>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D
Positions="1,1,-1 1,-1,-1 -1,-1,-1 -1,1,-1 1,1,1 -1,1,1 -1,-1,1 1,-1,1
1,1,-1 1,1,1 1,-1,1 1,-1,-1 1,-1,-1 1,-1,1 -1,-1,1 -1,-1,-1
-1,-1,-1 -1,-1,1 -1,1,1 -1,1,-1 1,1,1 1,1,-1 -1,1,-1 -1,1,1"
TriangleIndices="0 1 2 0 2 3 4 5 6 4 6 7 8 9 10 8 10 11 12 13 14 12 14
15 16 17 18 16 18 19 20 21 22 20 22 23"
TextureCoordinates="0,1 0,0 1,0 1,1 1,1 -0,1 0,-0 1,0 1,1 -0,1 0,-0
1,0 1,0 1,1 -0,1 0,-0 -0,0 1,-0 1,1 0,1 1,-0 1,1
0,1 -0,0" />
</GeometryModel3D.Geometry>
</GeometryModel3D>
</ModelUIElement3D.Model>
</ModelUIElement3D>
</Viewport3D.Children>
</Viewport3D>
</Grid>
</Window>
16.6. MainWindow.xaml.cs ,
using
using
using
using
System;
System.Windows;
System.Windows.Input;
System.Windows.Media;
660
16.
ContainerUIElement3D
ContainerUIElement3D
ModelUIElement3D:
<Viewport3D>
<Viewport3D.Children>
<ContainerUIElement3D>
<ModelUIElement3D ...>
<ModelUIElement3D ...>
</ContainerUIElement3D>
</Viewport3D.Children>
</Viewport3D>
ContainerUIElement3D Model3D,
Children Visual3DCollection .
ModelUIElement3DGroup.
ModelVisual3D UIEle
ment3D. ModelVisual3D Model3D,
Visual3DCollection. UIElement3D
ContainerUIElement3D ModelUIElement3D
.
Viewport2DVisual3D
WPF3.5 Viewport2DVisual3D
2D-
. 2D-
VisualBrush DrawingBrush.
, .
Button, VisualBrush,
. Viewport2DVisual3D :
, , .
TextBox, ,
.
,
. ,
TextBox!
Viewport2DVisual3D , , ,
, WPF.
Visual3D, . ,
, WPF Viewport2D.
16.7 Viewport2DVisual3D
Button. Viewport2DVisual3D MeshGeomet
ry3D, Material Visual.
Viewport2DVisual3D.
IsVisualHostMaterial true.
Brush, . , ,
Visual3D
661
Visual, .
.16.52.
16.7.
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Grid>
<Viewport3D>
<Viewport3D.Camera>
<PerspectiveCamera Position="0.2,0.1,1" LookDirection="-0.2,-.1,-1"
FieldOfView="120"/>
</Viewport3D.Camera>
<Viewport3D.Children>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight Direction="-0.3,-0.4,-0.5" />
</ModelVisual3D.Content>
</ModelVisual3D>
<Viewport2DVisual3D>
<Viewport2DVisual3D.Geometry>
<MeshGeometry3D Positions="-1,1,0 -1,-1,0 1,-1,0 1,1,0"
TextureCoordinates="0,0 0,1 1,1 1,0"
TriangleIndices="0 1 2 0 2 3" />
</Viewport2DVisual3D.Geometry>
<Viewport2DVisual3D.Material>
<DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial="True" />
</Viewport2DVisual3D.Material>
<Button>Hello, 3D</Button>
</Viewport2DVisual3D>
</Viewport3D.Children>
</Viewport3D>
</Grid>
</Window>
.16.52.
662
16.
Viewport2DVisual3D .
CacheMode, ,
UIElement.
,
, 3D-, ModelUIElement3D
MouseDown. ModelUIElement3D
3D-.
Visual, Visual3D
Visual.
Visual3D,
UIElement, 3D-,
Viewport3D:
<Viewport3D MouseDown="MouseDownHandler">
:
private void MouseDownHandler(object sender, MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
Viewport3D viewport = (Viewport3D)sender;
Point location = e.GetPosition(viewport);
HitTestResult result = VisualTreeHelper.HitTest(viewport, location);
if (result != null && result.VisualHit is Visual3D)
{
MessageBox.Show("Hit Visual3D!");
}
}
, Visual3D 15
VisualTreeHelper.HitTest,
.
3D-,
VisualTreeHelper.HitTest, Visual3D
HitTestParameters3D.
Viewport3D
663
HitTestResult , ,
PointHitTestResult GeometryHitTestResult.
HitTestResult ,
. ,
, 3D-, Hit
TestResult RayMeshGeometry3DHitTestResult.
.
Viewport3D
Viewport3D , Viewport2D
Visual3D. Viewport2DVisual3D Visual3D,
2D 3D, Viewport3D
FrameworkElement, 3D 2D.
Viewport3D , Window
Grid. Viewport3D Visual3D. 3D-
, Visual3D,
, Viewport3D. 3D- Viewport3D
Camera Viewport3D.
(. 21
) ,
. , Button
.
Viewport3D : Viewport3D
3D- ,
. ClipToBounds Viewport3D false,
3D-
. , Viewport3D
, true.
Width Height Viewport3D,
.
, Viewport3D 00 3D-
.
, Viewport3D
FrameworkElement, ,
3D- .
664
16.
3D-. .16.53
Photo Gallery 7
. ,
Button. ,
! .
16.8.
<!-- ,
. Viewport3D
" ",
Width Height,
. -->
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<ControlTemplate.Triggers>
<!-- -->
<Trigger Property="Button.IsPressed" Value="true">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard TargetName="RotateY" TargetProperty="Angle">
<DoubleAnimation Duration="0:0:1" From="0" To="360"
DecelerationRatio="1.0"/>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</ControlTemplate.Triggers>
<Viewport3D>
<Viewport3D.Camera>
<PerspectiveCamera Position="2.9,2.65,2.9" LookDirection="-1,-1,-1"/>
Viewport3D
665
</Viewport3D.Camera>
<Viewport3D.Children>
<ModelVisual3D x:Name="Light">
<ModelVisual3D.Content>
<DirectionalLight Direction="-0.3,-0.4,-0.5"/>
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D x:Name="Cube">
<ModelVisual3D.Transform>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D x:Name="RotateY" Axis="0,1,0" Angle="0"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
</ModelVisual3D.Transform>
<ModelVisual3D.Content>
<GeometryModel3D>
<GeometryModel3D.Material>
<DiffuseMaterial>
<DiffuseMaterial.Brush>
<!-- VisualBrush Background
Content -->
<VisualBrush ViewportUnits="Absolute" Transform="1,0,0,-1,0,1">
<VisualBrush.Visual>
<Border Background="{Binding Path=Background,
RelativeSource={RelativeSource TemplatedParent}}">
<Label Content="{Binding Path=Content,
RelativeSource={RelativeSource TemplatedParent}}"/>
</Border>
</VisualBrush.Visual>
</VisualBrush>
</DiffuseMaterial.Brush>
</DiffuseMaterial>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D
Positions="1,1,-1 1,-1,-1 -1,-1,-1 -1,1,-1 1,1,1 -1,1,1 -1,-1,1
1,-1,1 1,1,-1 1,1,1 1,-1,1 1,-1,-1 1,-1,-1 1,-1,1 -1,-1,1 -1,-1,-1
-1,-1,-1 -1,-1,1 -1,1,1 -1,1,-1 1,1,1 1,1,-1 -1,1,-1 -1,1,1"
TriangleIndices="0 1 2 0 2 3 4 5 6 4 6 7 8 9 10 8 10 11 12
13 14 12 14 15 16 17 18 16 18 19 20 21 22 20 22 23"
TextureCoordinates="0,1 0,0 1,0 1,1 1,1 0,1 0,-0 1,0 1,1
0,1 0,-0 1,0 1,0 1,1 0,1 0,-0 0,0 1,-0 1,1 0,1 1,-0
1,1 0,1 0,0"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D.Children>
</Viewport3D>
</ControlTemplate>
666
16.
</Setter.Value>
</Setter>
</Style>
Viewport3DVisual
Viewport3D Viewport3DVisual,
. Viewport3D
Visual - ,
Visual, FrameworkElement, Viewport3DVisual
Visual, Visual3D.
Viewport3DVisual , Viewport3D,
Viewport, ,
3D-, Visual
.
WPF
. ,
.
, , ,
.
, ,
.
.
API ,
.
Visual.TransformToAncestor
Visual TransformToAncestor,
GeneralTransform2DTo3D. , Visual Viewport2D
Visual3D.
Visual Visual3D.
16.9 16.10 (0,0), Viewport2D
Visual3D Button, ,
, Point3D,
. ,
, General
Transform2DTo3D. .16.54.
667
16.9. MainWindow.xaml
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Viewport3D Panel.ZIndex="0">
<Viewport3D.Camera>
<PerspectiveCamera Position="3,3,4" LookDirection="-1,-1,-1"
FieldOfView="60" />
</Viewport3D.Camera>
<Viewport3D.Children>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight Direction="-0.3,-0.4,-0.5" />
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D x:Name="Container">
<Viewport2DVisual3D>
<Viewport2DVisual3D.Transform>
<Transform3DGroup>
<TranslateTransform3D OffsetX="1.5" />
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D x:Name="rotationY" Axis="0,1,0" Angle="0" />
</RotateTransform3D.Rotation>
</RotateTransform3D>
</Transform3DGroup>
</Viewport2DVisual3D.Transform>
<Viewport2DVisual3D.Geometry>
668
16.
669
</Viewport3D.Children>
</Viewport3D>
</Grid>
<Window.Triggers>
<EventTrigger RoutedEvent="Window.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="rotationY"
Storyboard.TargetProperty="Angle"
From="0" To="360" Duration="0:0:12"
RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Window.Triggers>
</Window>
16.10. MainWindow.xaml.cs ,
using
using
using
using
System;
System.Windows;
System.Windows.Media;
System.Windows.Media.Media3D;
670
16.
16.10 CompositionTarget.Rendering ,
. , -
.
, EventArgs
RenderingEventArgs, RenderingTime (
).
Visual3D.TransformToAncestor
Visual3D.TransformToDescendant
Visual3D
. GeneralTransform3DTo2D,
Visual3D.TransformToAncestor,
Visual3D .
,
,
.
16.11 16.12 TransformToAncestor ,
TextBlock ,
.16.55.
16.11. MainWindow.xaml
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid Name="myGrid">
<TextBlock Panel.ZIndex="1" IsHitTestVisible="False">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="t_000" />
</TextBlock.RenderTransform>
(-1,-1,-1)
</TextBlock>
<TextBlock Panel.ZIndex="1" IsHitTestVisible="False">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="t_001" />
</TextBlock.RenderTransform>
(-1,-1,1)
</TextBlock>
<TextBlock Panel.ZIndex="1" IsHitTestVisible="False">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="t_010" />
</TextBlock.RenderTransform>
(-1,1,-1)
</TextBlock>
<TextBlock Panel.ZIndex="1" IsHitTestVisible="False">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="t_011" />
</TextBlock.RenderTransform>
(-1,1,1)
</TextBlock>
<TextBlock Panel.ZIndex="1" IsHitTestVisible="False">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="t_100" />
</TextBlock.RenderTransform>
(1,-1,-1)
</TextBlock>
<TextBlock Panel.ZIndex="1" IsHitTestVisible="False">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="t_101" />
</TextBlock.RenderTransform>
(1,-1,1)
</TextBlock>
<TextBlock Panel.ZIndex="1" IsHitTestVisible="False">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="t_110" />
</TextBlock.RenderTransform>
(1,1,-1)
</TextBlock>
<TextBlock Panel.ZIndex="1" IsHitTestVisible="False">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="t_111" />
</TextBlock.RenderTransform>
(1,1,1)
</TextBlock>
<Viewport3D Panel.ZIndex="0">
<Viewport3D.Camera>
<PerspectiveCamera Position="3,3,4" LookDirection="-1,-1,-1"
FieldOfView="60"/>
</Viewport3D.Camera>
<Viewport3D.Children>
<ModelVisual3D>
<ModelVisual3D.Content>
<DirectionalLight Direction="-0.3,-0.4,-0.5" />
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelUIElement3D x:Name="Cube">
<ModelUIElement3D.Transform>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D x:Name="rotationY" Axis="0,1,0" Angle="0" />
</RotateTransform3D.Rotation>
</RotateTransform3D>
</ModelUIElement3D.Transform>
<ModelUIElement3D.Model>
<GeometryModel3D x:Name="OB_Cube">
<GeometryModel3D.Material>
<DiffuseMaterial>
<DiffuseMaterial.Brush>
<SolidColorBrush Color="Orange" x:Name="CubeBrush" />
671
672
16.
</DiffuseMaterial.Brush>
</DiffuseMaterial>
</GeometryModel3D.Material>
<GeometryModel3D.Geometry>
<MeshGeometry3D x:Name="ME_Cube2"
Positions="1,1,-1 1,-1,-1 -1,-1,-1 -1,1,-1 1,1,1 -1,1,1 -1,-1,1
1,-1,1 1,1,-1 1,1,1 1,-1,1 1,-1,-1 1,-1,-1 1,-1,1
-1,-1,1 -1,-1,-1 -1,-1,-1 -1,-1,1 -1,1,1 -1,1,-1 1,1,1
1,1,-1 -1,1,-1 -1,1,1"
TriangleIndices="0 1 2 0 2 3 4 5 6 4 6 7 8 9 10 8 10 11 12 13 14
12 14 15 16 17 18 16 18 19 20 21 22 20 22 23"
TextureCoordinates="0,1 0,0 1,0 1,1 1,1 -0,1 0,-0 1,0 1,1 -0,1
0,-0 1,0 1,0 1,1 -0,1 0,-0 -0,0 1,-0 1,1 0,1
1,-0 1,1 0,1 -0,0"/>
</GeometryModel3D.Geometry>
</GeometryModel3D>
</ModelUIElement3D.Model>
</ModelUIElement3D>
</Viewport3D.Children>
</Viewport3D>
</Grid>
<Window.Triggers>
<EventTrigger RoutedEvent="Window.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="rotationY"
Storyboard.TargetProperty="Angle"
From="0" To="360" Duration="0:0:12"
RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Window.Triggers>
</Window>
.16.55.
673
16.12. MainWindow.xaml.cs ,
using
using
using
using
using
System;
System.Windows;
System.Windows.Input;
System.Windows.Media;
System.Windows.Media.Media3D;
674
16.
GeneralTransform3DTo2D,
Grid.
.
,
. ,
CompositionTarget.Rendering.
Visual3D
TransformToDescendant Trans
formToAncestor: GeneralTransform3D,
Visu
al3D .
, , , API WPF
API. .16.1
, 3D- ,
. WPF
,
.
3D-, WPF,
, ,
. 3D- WPF
.
, . 3D-
(DataTemplate)
(ControlTemplate). ,
.
API, ,
. 19
D3DImage, Direct3D.
, 3D
.
, ,
.
XAML-
17
17.
WPF
. ,
!
, ,
, . ,
Adobe Flash,
,
. iPhone, iPad, Windows-
, Xbox Windows 7 ( )
. , ,
.
, Microsoft Expres
sion Blend, WPF ,
Adobe Flash. , WPF API
,
.
, ,
C# XAML.
WPF
. ,
XAML,
. ,
/
. ,
(VSM).
676
17.
, ,
,
. WPF :
. - ,
, ,
Width, .
,
,
, WPF.
.
WPF, .
,
.
(
) ,
.
/ .
,
WPF. WPF DispatcherTimer,
.
Interval, Tick.
Windows-
, .
,
WPF.
,
,
Rendering System.Windows.Media.CompositionTarget.
,
. ( ,
enterFrame Adobe Flash,
.)
Rendering
,
, ,
, , .
,
.
677
. Rendering
(
),
. WPF ,
-
. Rendering ,
. Rendering
.
DispatcherTimer .NET
DispatcherTimer ,
System.Threading.Timer System.Timers.Timer, ,
DispatcherTimer
. WPF- ,
UIElement ,
.
Dispatcher. :
void Callback(object sender, EventArgs e)
{
// DoTheRealWork :
this.Dispatcher.Invoke(DispatcherPriority.Normal,
new TimerDispatcherDelegate(DoTheRealWork));
}
Dispatcher.Invoke .
, Dispatcher.BeginInvoke.
DispatcherTimer :
void Callback(object sender, EventArgs e)
{
//
}
DispatcherTimer
DispatcherPriority, Background, Dispat
cherTimer DispatcherPriority.
CompositionTarget.Rendering
, WPF
.
System.Windows.Media.Animation ,
678
17.
.
, ,
.
:
.
WPF ,
,
DispatcherTimer Rendering.
,
. WPF
,
WPF
; ! WPF
,
.
System.Windows.Media.Animation
,
. ,
, double,
DoubleAnimation.
Thickness, ThicknessAnimation. WPF
22 ; .17.1.
17.1. ,
.NET
WPF
Boolean
Thickness
Byte
Color
Char
Size
Decimal
Rect
Int16
Point
Int32
Point3D
Int64
Vector
Single
Vector3D
Double
Rotation3D
String
Matrix
Object
Quaternion
679
System.Windows.Media.Animation :
22 XXXAnimationBase
17 XXXAnimation
22 XXXAnimationUsingKeyFrames
22 XXXKeyFrameCollection
22 XXXKeyFrame
22 DiscreteXXXKeyFrame
17 LinearXXXKeyFrame
17 SplineXXXKeyFrame
17 EasingXXXKeyFrame
3 XXXAnimationUsingPath
( XXX .17.1.)
, 10
181 ! , .NET,
, :
WPF ?
, Animation<T>,
double Animation<double>,
Thickness Animation<Thickness> ..?
( ) ,
XAML2009
XAML . ,
, ,
. , Animation<T> ,
,
Animation<Window>.
, , .
, , double.
double ,
,
double.
, Width Button 50 100.
Canvas:
<Window x:Class="Window1" Title="Animation" Width="300" Height="300"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
680
17.
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Canvas>
<Button x:Name="b">OK</Button>
</Canvas>
</Window>
Width 50 100
DoubleAnimation:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
//
DoubleAnimation a = new DoubleAnimation();
a.From = 50;
a.To = 100;
//
b.BeginAnimation(Button.WidthProperty, a);
}
}
DoubleAnimation
double double. BeginAnima
tion Button,
Width . ,
, 50 100
.
From To ,
.
.
, Completed, ,
.
, double
. (
!)
, Width 55
0,1 (5% , ), 75
0,5 (50% ) ..
681
,
, ,
.
.17.1 . ( , Boolean
String, .)
,
, . .
,
Visibility,
Hidden Visible .
Opacity double, 0 1.
, , Grid,
,
Grid.Column Int32Animation,
.
TranslateTransform RenderTrans
form, X ( double)
DoubleAnimation.
Width Grid (
: , ,
, Visual Studio 5
) , ColumnDefi
nition.Width GridLength,
. MinWidth
/ MaxWidth ColumnDefinition, double,
Width Auto,
, Width .
BeginAnimation. BeginAnimation
. ,
, Height
Window Width :
this.BeginAnimation(Window.HeightProperty, a);
.17.1. (
, ,
,
,
Expander.
.)
682
17.
(Value = 50)
(Value = 75)
(Value = 100)
.17.1. DoubleAnimation
50 100
Doub
leAnimation 1 ,
Duration:
DoubleAnimation a = new DoubleAnimation();
a.From = 50;
a.To = 100;
a.Duration = new Duration(TimeSpan.Parse("0:0:5"));
, Duration TimeSpan !
TimeSpan.Parse, Duration
XAML, ,
.::._
. . "2"
2 , 2 ! "2.5" 2 5 ! "0:2"
2 . , , ,
, ::
::._. , 2
"0:0:2", "0:0:0.5" "0:0:.5".
683
.17.1 5 . Dura
tion TimeSpan, .NET
Framework .
TimeSpan.Parse
.::._.
Duration TimeSpan
, WPF Duration
TimeSpan, , Duration ,
TimeSpan: Duration.Automatic Duration.
Forever.
, Storyboard (. ).
Automatic Duration
, TimeSpan 1 .
Forever , DoubleAnimation,
. WPF
!
From To
.17.1 Width
Height 50 100, 50
. ,
. BeginAnimation
, .
, To Width/Height
50,
ActualWidth Button 100,
ActualHeight Window 100. , .
From . ,
, .
, ,
:
DoubleAnimation a = new DoubleAnimation();
// : a.From = 50;
a.To = 100;
a.Duration = new Duration(TimeSpan.Parse("0:0:5"));
, , Width
(, "OK",
) 100 5 .
AnimationException :
684
17.
Width ,
NaN. NaN 100!
, ActualWidth (
, NaN) Width ,
.
, -
Width . :
<!--
From: -->
<Button x:Name="b" Width="20">OK</Button>
From ,
.
, 50 100
,
50. From ,
,
, . ,
MouseEnter MouseLeave,
, From ,
,
.
To !
, 50 20
( ) 5 :
DoubleAnimation a = new DoubleAnimation();
a.From = 50;
// : a.To = 100;
a.Duration = new Duration(TimeSpan.Parse("0:0:5"));
By,
To. 100 ( 150),
100:
685
By From :
100 .
DoubleAnimation a = new DoubleAnimation();
a.By = 100; // a.To = currentValue + 100;
:
DoubleAnimation a = new DoubleAnimation();
a.By = -100; // a.To = currentValue - 100;
: From, To,
Duration, By. ,
.
By, -
, ,
. ,
XAML.
BeginTime
,
BeginAnimation, ,
BeginTime TimeSpan:
DoubleAnimation a = new DoubleAnimation();
// 5 :
a.BeginTime = TimeSpan.Parse("0:0:5");
a.From = 50;
a.To = 100;
a.Duration = new Duration(TimeSpan.Parse("0:0:5"));
,
. BeginTime
:
DoubleAnimation a = new DoubleAnimation();
// :
a.BeginTime = TimeSpan.Parse("-0:0:2.5");
a.From = 50;
a.To = 100;
a.Duration = new Duration(TimeSpan.Parse("0:0:5"));
, 2,5
( 2,5
686
17.
TimeSpan.Parse,
, TimeSpan (, , ,
XAML).
TimeSpan, FromSeconds
FromMilliseconds.
SpeedRatio
SpeedRatio , Duration.
1, double,
0:
DoubleAnimation a = new DoubleAnimation();
a.BeginTime = TimeSpan.Parse("0:0:5");
// :
a.SpeedRatio = 2;
a.From = 50;
a.To = 100;
a.Duration = new Duration(TimeSpan.Parse("0:0:5"));
, 1, , 1
. SpeedRatio BeginTime;
5- , 50 100
2,5 5.
AutoReverse
AutoReverse true,
.
, . ,
50 100 5 100 50 5 :
DoubleAnimation a = new DoubleAnimation();
a.AutoReverse = true;
a.From = 50;
a.To = 100;
a.Duration = new Duration(TimeSpan.Parse("0:0:5"));
SpeedRatio .
SpeedRatio = 2,
5 , SpeedRatio = 0.5, 20 .
687
, , BeginTime,
;
.
RepeatBehavior
RepeatBehavior :
,
RepeatBehavior double:
DoubleAnimation a = new DoubleAnimation();
// :
a.RepeatBehavior = new RepeatBehavior(2);
a.AutoReverse = true;
a.From = 50;
a.To = 100;
a.Duration = new Duration(TimeSpan.Parse("0:0:5"));
AutoReverse true, .
20
: 50 100 50 100 50. BeginTime ,
. double,
.
, Repeat
Behavior RepeatBehavior.Forever:
a.RepeatBehavior = RepeatBehavior.Forever;
,
RepeatBehavior TimeSpan, double.
:
DoubleAnimation a = new DoubleAnimation();
// :
a.RepeatBehavior = new RepeatBehavior(TimeSpan.Parse("0:0:20"));
a.AutoReverse = true;
a.From = 50;
a.To = 100;
a.Duration = new Duration(TimeSpan.Parse("0:0:5"));
20 ,
AutoReverse true. , SpeedRatio
688
17.
TimeSpan, RepeatBehavior,
; SpeedRatio = 2,
20 .
RepeatBehavior
, ,
TimeSpan , .
50 75 2,5 :
DoubleAnimation a = new DoubleAnimation();
// :
a.RepeatBehavior = new RepeatBehavior(TimeSpan.Parse("0:0:2.5"));
a.From = 50;
a.To = 100;
a.Duration = new Duration(TimeSpan.Parse("0:0:5"));
,
BeginTime, SpeedRatio, AutoReverse RepeatBehavior,
, .
Duration !
:
= BeginTime +
Duration * (AutoReverse ? 2 : 1)
* RepeatBehavior
SpeedRatio
, RepeatBehavior
double (
1). RepeatBehavior TimeSpan,
RepeatBehavior BeginTime.
689
,
.
, (100%).
. 17.2 , AccelerationRatio
DecelerationRatio .
AccelerationRatio = 1
AccelerationRatio = 0.33
WPF4 EasingFunction,
, IEas
ingFunction.
. WPF 11 , IEas
ingFunction, (
, ).
. .
IsAdditive IsCumulative
IsAdditive true, (
) From To
.
RepeatBehavior, ,
. , ,
, , ,
.
690
17.
FillBehavior
, ,
, , -
. , , ,
,
FillBehavior Stop (
HoldEnd).
XAML-
,
XAML-. :
<DoubleAnimation From="50" To="100" Duration="0:0:5" AutoReverse="True"/>
?
,
BeginAnimation.
,
, .
, , WPF
XAML. ,
, Setter, .
,
,
.
.
3 WPF , (
EventTrigger)
. Ro
utedEvent, (
, TriggerAction) Actions.
, DoubleAnimation, ,
Actions .
XAML-
691
Storyboard (
), BeginStoryboard.
, DoubleAnima
tion , ,
:
<Button>
OK
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard TargetProperty="Width">
<DoubleAnimation From="50" To="100"
Duration="0:0:5" AutoReverse="True"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
</Button>
, BeginAnimation
: Storyboard TargetProperty
, , BeginSto
ryboard , Storyboard .
, BeginStoryboard , WPF
, TriggerAction.
,
BeginStoryboard
, , .. ( PauseStoryboard,
SeekStoryboard ..)
XAML , Storyboard.
XAML- TargetProperty Story
board (Width) .
TargetProperty PropertyPath, ,
( ),
.
Button, Background
- LinearGradientBrush
692
17.
GradientStop. ColorAnimation,
Color . (
, Color
,
ScA, ScR, ScB ScG, ColorAnimation
, DoubleAnimation .)
- Storyboard
TargetProperty:
<Button Padding="30">
OK
<Button.Background>
<LinearGradientBrush>
<GradientStop Color="Blue" Offset="0"/>
<GradientStop Color="Black" Offset="0.5"/>
<GradientStop Color="Blue" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard TargetProperty="Background.GradientStops[1].Color">
<ColorAnimation From="Black" To="White" Duration="0:0:2"
AutoReverse="True" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Button.Triggers>
</Button>
TargetProperty , C#
, .
, Background
, GradientStops, ,
Color Color.
, . ,
, ,
.17.3.
.17.3. -
XAML-
693
DoubleAnimation Background.
GradientStops[1].Offset ,
.
Color Offset Loaded,
BeginStoryboard:
<EventTrigger RoutedEvent="Button.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard TargetProperty="Background.GradientStops[1].Color">
<ColorAnimation From="Black" To="White" Duration="0:0:2"
AutoReverse="True" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
<BeginStoryboard>
<Storyboard TargetProperty="Background.GradientStops[1].Offset">
<DoubleAnimation From="0" To="1" Duration="0:0:2"
AutoReverse="True" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
, WPF
Storyboard. -, Storyboard
. Storyboard
Children, Timeline (
). -, TargetProperty ,
,
Storyboard! XAML-
:
<EventTrigger RoutedEvent="Button.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation From="Black" To="White" Duration="0:0:2"
Storyboard.TargetProperty="Background.GradientStops[1].Color"
AutoReverse="True" RepeatBehavior="Forever"/>
<DoubleAnimation From="0" To="1" Duration="0:0:2"
Storyboard.TargetProperty="Background.GradientStops[1].Offset"
AutoReverse="True" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
,
.
, , , ,
BeginTime.
694
17.
,
, . ,
, Style -.
, TargetName Sto
ryboard. TargetProperty, TargetName
Storyboard,
.
TargetName
, :
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Grid.Triggers>
<EventTrigger RoutedEvent="Grid.Loaded">
<BeginStoryboard>
<Storyboard TargetName="jim2" TargetProperty="Opacity">
<DoubleAnimation From="1" To="0" Duration="0:0:4"
AutoReverse="True" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Grid.Triggers>
<Image Name="jim1" Source="jim1.gif"/>
<Image Name="jim2" Source="jim2.gif"/>
</Grid>
,
. .17.4.
Opacity = 1
Opacity = 0.5
Opacity = 0
XAML-
695
TargetName ,
jim2,
Grid. (, -
Image)
, , Storyboard.
, TargetName
.
XAML-
.
Style. 17.1 StackPanel
.
MouseEnter MouseLeave,
.
.17.5.
17.1.
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Animation">
<Window.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="VerticalAlignment" Value="Bottom"/>
<Setter Property="LayoutTransform">
<Setter.Value>
<ScaleTransform/>
</Setter.Value>
</Setter>
<Style.Triggers>
<EventTrigger RoutedEvent="Button.MouseEnter">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="LayoutTransform.ScaleX"
To="2" Duration="0:0:0.25"/>
<DoubleAnimation Storyboard.TargetProperty="LayoutTransform.ScaleY"
To="2" Duration="0:0:0.25"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="Button.MouseLeave">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="LayoutTransform.ScaleX"
To="1" Duration="0:0:0.25"/>
<DoubleAnimation Storyboard.TargetProperty="LayoutTransform.ScaleY"
To="1" Duration="0:0:0.25"/>
696
17.
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel Orientation="Horizontal">
<Button>1</Button>
<Button>2</Button>
<Button>3</Button>
<Button>4</Button>
<Button>5</Button>
<Button>6</Button>
<Button>7</Button>
<Button>8</Button>
</StackPanel>
</Window>
.17.5.
TargetProperty
ScaleX ScaleY .
, LayoutTransform
ScaleTransform. LayoutTransform
TransformGroup, ScaleTransform
,
LayoutTransform.Children[0].ScaleX LayoutTransform.Child
ren[0].ScaleY.
ScaleTransform / TranslateTransform
. ScaleX ScaleY ScaleTransform
, Width Height,
, .
TranslateTransform , - Can
vas.Left Canvas.Top, ,
.
XAML-
697
RepeatBehavior, Duration, ,