15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

M a r k u p e x t e n s i o n s ❘ 741<br />

{<br />

public partial class MainWindow : Window<br />

{<br />

public MainWindow()<br />

{<br />

InitializeComponent();<br />

MyAttachedPropertyProvider.SetMyProperty(button1, 44);<br />

}<br />

}<br />

}<br />

foreach (object item in LogicalTreeHelper.GetChildren(grid1))<br />

{<br />

FrameworkElement e = item as FrameworkElement;<br />

if (e != null)<br />

list1.Items.Add(String.Format(“{0}: {1}”, e.Name,<br />

MyAttachedPropertyProvider.GetMyProperty(e)));<br />

}<br />

code snippet AttachedPropertyDemo/MainWindow.xaml.cs<br />

There are some mechanisms available to extend classes at a later time. Extension<br />

methods can be used to extend any class with methods. Extension methods only<br />

support extending classes with methods, not properties. Extension methods are<br />

explained in Chapter 3, “ Objects <strong>and</strong> Types. ” The Exp<strong>and</strong>oObject class allows the<br />

extension of types with methods <strong>and</strong> properties. To use this feature, the class must<br />

derive from Exp<strong>and</strong>oObject . Exp<strong>and</strong>oObject <strong>and</strong> dynamic types are explained in<br />

Chapter 12, “ Dynamic Language Extensions. ”<br />

Chapters 35 <strong>and</strong> 36 show many different attached properties in action, for example<br />

attached properties from container controls such as Canvas , DockPanel , Grid , but also<br />

the ErrorTemplate property from the Validation class.<br />

marKuP eXTensions<br />

With markup extensions you can extend XAML, with either element or attribute syntax. If an XML<br />

attribute contains curly brackets, that ’ s a sign of a markup extension. Often markup extensions with<br />

attributes are used as shorth<strong>and</strong> notation instead of using elements.<br />

One example of such a markup extension is StaticResourceExtension , which fi nds resources. Here ’ s a<br />

resource of a linear gradient brush with the key gradientBrush1 .<br />

< Window.Resources ><br />

< LinearGradientBrush x:Key="gradientBrush1" StartPoint="0.5,0.0" EndPoint="0.5, 1.0" ><br />

< GradientStop Offset="0" Color="Yellow" / ><br />

< GradientStop Offset="0.3" Color="Orange" / ><br />

< GradientStop Offset="0.7" Color="Red" / ><br />

< GradientStop Offset="1" Color="DarkRed" / ><br />

< /LinearGradientBrush ><br />

< /Window.Resources ><br />

code snippet MarkupExtensionDemo/MainWindow.xaml<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!