15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1058 ❘ ChaPTer 36 business ApplicAtiOns with wpf<br />

In the constructor of the MainWindow class, a new object of the class SomeData is initialized <strong>and</strong> passed to<br />

the DataContext for data binding:<br />

public partial class MainWindow: Window<br />

{<br />

private SomeData p1 = new SomeData { Value1 = 11 };<br />

public MainWindow()<br />

{<br />

InitializeComponent();<br />

this.DataContext = p1;<br />

}<br />

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

The event h<strong>and</strong>ler method OnShowValue displays a message box to show the actual value of the SomeData<br />

instance:<br />

}<br />

private void OnShowValue(object sender, RoutedEventArgs e)<br />

{<br />

MessageBox.Show(p1.Value1.ToString());<br />

}<br />

With simple data binding, here the Text property of a TextBox is bound to the Value1 property. If you run<br />

the application now <strong>and</strong> try to change the value to one that is not valid, you can verify that the value never<br />

changed by clicking the Submit button. WPF catches <strong>and</strong> ignores the exception thrown by the set accessor<br />

of the property Value1:<br />

Value1:<br />

<br />

code snippet ValidationDemo/MainWindow.xaml<br />

To display an error as soon as the context of the input field changes, you can set the ValidatesOnException<br />

property of the Binding markup extension to True. With an invalid value (as soon as the exception is thrown<br />

when the value should be set), the TextBox is surrounded by a red line, as shown in Figure 36-11.<br />

Value1:<br />

<br />

To return the error information in a different way to the user, you can assign<br />

the attached property ErrorTemplate that is defined by the Validation<br />

class to a template defining the UI for errors. The new template to mark the error<br />

is shown here with the key validationTemplate. The ControlTemplate puts a<br />

red exclamation point in front of the existing control content:<br />

<br />

<br />

!<br />

<br />

<br />

<br />

Setting the validationTemplate with the Validation.ErrorTemplate attached<br />

property activates the template with the TextBox:<br />

Value1:<br />

<br />

The new look of the application is shown in Figure 36-12.<br />

www.it-ebooks.info<br />

figure 36-11<br />

figure 36-12

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

Saved successfully!

Ooh no, something went wrong!