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.

734 ❘ ChaPTer 27 COre xAml<br />

}<br />

set { SetValue(ValueProperty, value); }<br />

}<br />

}<br />

public static readonly DependencyProperty ValueProperty =<br />

DependencyProperty.Register("Value", typeof(int), typeof(MyDependencyObject));<br />

public int Minimum<br />

{<br />

get { return (int)GetValue(MinimumProperty); }<br />

set { SetValue(MinimumProperty, value); }<br />

}<br />

public static readonly DependencyProperty MinimumProperty =<br />

DependencyProperty.Register("Minimum", typeof(int), typeof(MyDependencyObject),<br />

new PropertyMetadata(0));<br />

public int Maximum<br />

{<br />

get { return (int)GetValue(MaximumProperty); }<br />

set { SetValue(MaximumProperty, value); }<br />

}<br />

public static readonly DependencyProperty MaximumProperty =<br />

DependencyProperty.Register("Maximum", typeof(int), typeof(MyDependencyObject),<br />

new PropertyMetadata(100));<br />

code snippet DependencyObjectDemo/MyDependencyObject.cs<br />

W i t hi n t he get <strong>and</strong> set property accessors you may not do more than just calling the<br />

GetValue() <strong>and</strong> SetValue() methods. Using the dependency properties, the property<br />

values can be accessed from the outside with the GetValue() <strong>and</strong> SetValue() methods,<br />

which is also done from WPF, <strong>and</strong> thus, the strongly - typed property accessors might not<br />

be invoked at all. They are just here for convenience for custom code.<br />

Coerce Value Callback<br />

Dependency properties support coercion. With coercion, the value of the property can be checked to see if<br />

it is valid, for example, that it falls within a valid range. That ’ s why the Minimum <strong>and</strong> Maximum properties<br />

are included in the sample. Now the registration of the Value property is changed to pass the event h<strong>and</strong>ler<br />

method CoerceValue() to the constructor of PropertyMetadata , which is passed as an argument to<br />

the DependencyProperty.Register() method. The CoerceValue() method is now invoked with every<br />

change of the property value from the implementation of the SetValue() method. Within CoerceValue() ,<br />

the set value is checked to see if it falls within the range between the minimum <strong>and</strong> maximum, <strong>and</strong> the<br />

value is set accordingly if this is not the case.<br />

using System;<br />

using System.Windows;<br />

namespace Wrox.ProCSharp.XAML<br />

{<br />

class MyDependencyObject : DependencyObject<br />

{<br />

public int Value<br />

{<br />

get { return (int)GetValue(ValueProperty); }<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!