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.

Data Binding ❘ 1053<br />

adding list items dynamically<br />

What if list items are added dynamically The WPF element must be notified of elements added to the list.<br />

In the XAML code of the WPF application, a Button element is added inside a StackPanel. The Click<br />

event is assigned to the method OnAddBook():<br />

<br />

<br />

<br />

code snippet BooksDemo/BooksUC.xaml<br />

In the method OnAddBook(), a new Book object is added to the list. If you test the application with the<br />

BookFactory as it is implemented now, there’s no notification to the WPF elements that a new object has<br />

been added to the list:<br />

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

{<br />

((this.FindResource("books") as ObjectDataProvider).Data as<br />

IList).Add(<br />

new Book(".<strong>NET</strong> 3.5 Wrox Box", "Wrox Press",<br />

"978-0470-38799-3"));<br />

}<br />

code snippet BooksDemo/BooksUC.xaml.cs<br />

The object that is assigned to the DataContext must implement the interface INotifyCollectionChanged.<br />

This interface defines the CollectionChanged event that is used by the WPF application. Instead of<br />

implementing this interface on your own with a custom collection class, you can use the generic collection<br />

class ObservableCollection that is defined with the namespace System.Collections.ObjectModel<br />

in the assembly WindowsBase. Now, as a new item is added to the collection, the new item immediately<br />

shows up in the ListBox:<br />

public class BookFactory<br />

{<br />

private ObservableCollection books =<br />

new ObservableCollection();<br />

// ...<br />

}<br />

public IEnumerable GetBooks()<br />

{<br />

return books;<br />

}<br />

code snippet BooksDemo/Utilities/BookFactory.cs<br />

data Template selector<br />

In the previous chapter, you saw how controls can be customized with templates. You also saw how to<br />

create a data template that defines a display for specific data types. A data template selector can create<br />

different data templates dynamically for the same data type. A data template selector is implemented in a<br />

class that derives from the base class DataTemplateSelector.<br />

Here a data template selector is implemented by selecting a different template based on the publisher. Within<br />

the user control resources these templates are defined. One template can be accessed by the key name<br />

wroxTemplate; the other template has the key name dummiesTemplate, <strong>and</strong> the third one bookTemplate:<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!