Prezentace se nahrává, počkejte prosím

Prezentace se nahrává, počkejte prosím

Windows Presentation Foundation Data Binding

Podobné prezentace


Prezentace na téma: "Windows Presentation Foundation Data Binding"— Transkript prezentace:

1 Windows Presentation Foundation Data Binding

2 Co je to Data Binding? Proces propojení UI s aplikační logikou
Jednoduchá synchronizace dat s visuální reprezentací Reflektuje na změny v UI i v datovém zdroji WPF propojuje tzv. Dependency Properties s řadou datových zdrojů – CLR objekty a XML dokumenty Dependency Property – vlastnost UI elementu s podporou value expressions, property invalidation, implicitními hodnotami, dědičností, databinding a stylování

3 Data binding - přehled Cíl (Binding Target) Zdroj (Binding Source)
Ovládací prvek Cíl (Binding Target) Libovolná vlastnost WPF elementu Zdroj (Binding Source) CLR objekt WPF Element ADO.NET (prostřednictvím Dataset) XML Kolekce Modely One Time, One Way, Two Way, One Way To Source Dynamika Master-Detail scénáře Value Converter Dependency Property Data Binding Synchronizace Konverze WPF’s data binding system can target any property on any WPF element. (Strictly speaking, the target has to be a Dependency Property, which almost all properties on WPF elements are.) Absolutely any public property on any .NET object can be used as a data source. The object does not need to have any special knowledge of WPF. The property simply has to be a normal CLR property. This is crucial to data binding’s flexibility – it places very few demands on the source object, giving you freedom to choose more or less any object as a source. Data binding also recognizes the .NET Framework’s TypeDescriptor property virtualization system, that allows objects to decide at runtime what properties to expose. This is the system used by the ADO.NET DataSet, DataTable, and related classes to present whatever columns of data happen to be in the table. Finally, data binding has special handling for XML data sources. Zdroj Objekt Property

4 Směr toku dat OneWay TwoWay OneWayToSource OneTime
Změna ve zdroji dat je automaticky propagována do UI Typicky pro Read-only vlastnosti UI elementů TwoWay Změny ve zdroji dat i UI jsou navzájem synchronizovány Např. Editbox, CheckBox atd. OneWayToSource Propagovány jsou pouze změny v UI zpět do datového zdroje OneTime Zdroj inicializuje cíl pouze 1x Typicky pro statický obsah nebo zobrazení aktuálního stavu Důležité: datové zdroje pro OneWay a TwoWay scénáře musí podporovat „upozorňovací mechanismus“ Implementovat rozhraní INotifyPropertyChanged (u kolekcí také INotifyCollectionChanged)

5 Data binding v XAML <Image Source="auto.png" Canvas.Left=
"{Binding Path = Value, ElementName = pozice }" /> <Slider Orientation= "Horizontal" Name = “pozice" Value = "40" Maximum="100" /> The most straightforward form of data binding to look at is binding between one element and another in the user interface. There’s nothing special about this – it works like binding to any data source, it’s just easier to see what’s going on because everything can be shown in markup. Here we have a UI with a horizontal slider control, and we’d like to use that to set the position of an image. We can do this by using data binding to bind the image’s Canvas.Left property to the horizontal slide’s Value property. The binding expression for this needs just two pieces of information: the name of the property (which we set as the Path of the binding) and the name of the source element. Setting the binding’s ElementName property lets the binding know that we want to bind to a UI element. (There are other properties used for other source types.)

6 Datový kontext <Window …> <Grid …>
Datový kontext je místo, kde data binding hledá informace zdroji dat Definován na úrovni každého FrameworkElementu a FrameworkContentElementu Hledání zdroje dat začíná u elementu samotného a postupuje směrem ke kořeni dokumentu <Window …> 3 2 <Grid …> 1 <TextBox Text = "{Binding Path=Jmeno}“ … />

7 Sdílení společných zdrojů
DataContext= {Binding Source={StaticResource mojeData}} StackPanel HorizontalSlider Value= {Binding Path=PoziceX} Value= {Binding Path=PoziceX, Source={StaticResource mojeData}} Image It is common for many UI elements to want to display various different properties from the same data source object. It would be tedious for each of these to have to specify the source. This would result in a lot of repetition, and would also make it more effort to modify the UI. The DataContext property solves this problem. If a Binding does not have a Source specified, then the source is presumed to be the element’s DataContext. And if an element’s DataContext has not been set explicitly, it will use its parent’s DataContext. This means that you can make a data source object available to all the descendants of an element by setting the DataContext on that one element. This simplifies the Binding expressions for all of the children. (Assuming they all want to use the same source object that is.) Canvas.Left= {Binding Path=PoziceX, Source={StaticResource mojeData}} Canvas.Left= {Binding Path=PoziceX}

8 Nastavení zdroje dat Deklarativně v XAML V kódu aplikace
<Window … xmlns:local="clr-namespace:Demo"> <Window.Resources> <local:Kontakt x:Key="Dali" Jmeno="Dalibor" Telefon=" " /> <local:Kontakt x:Key=“Gabi" Jmeno=“Gabi" Telefon=" " /> </Window.Resources> Explicitní binding <TextBox Text="{Binding Path=Jmeno, Source={StaticResource Dali}}"> V kódu aplikace Kontakt kt = new Kontakt("Dalibor“, ); grid.DataContext = kt; Implicitní binding <TextBox Text="{Binding Path=Telefon}">

9 Video ukázka Jednoduchý data binding, sdílení datového zdroje
Demo I: Simple Bindings Reflections

10 Objektový datový zdroj
ObjectDataProvider umožňuje provést instanci libovolného typu v XAML kódu a vytvořit z něj datový zdroj Možnost spuštění konstruktoru ve vlastním threadu <Window> <Window.Resources> <ObjectDataProvider x:Key="mojeData" ObjectType="{x:Type local:Data}" IsAsynchronous="true" /> </Window.Resources> <TextBlock TextContent="{Binding Path=Jmeno, Source={StaticResource mojeData} }" /> Data binding to other objects in the UI is sometimes useful, but it’s a bit limited. So you will often want to bind to other objects. The usual way of making an object available for binding is to add it to a resource dictionary. Every UI element has a resource dictionary in it. Each element has access not only to its own dictionary, but also to its parent’s dictionary, its parent’s parent, and so on. There’s also an application-wide resource dictionary. We can place an object in here, and then use WPF’s resource binding syntax, {StaticResource nameOfObject} to retrieve a reference to that object. This resource binding syntax can be used for all sorts of things, but here we’re using it to set the Source of the Binding. Notice that we’re now using Source rather than ElementName on the binding. Rather than telling the Binding to use a named UI element as the source, this hands it a reference directly to the source. Here we’re putting the object into the resource dictionary with the ObjectDataProvider element. This creates an object of the specified type (in this case, a class called Foo). The purpose of this element is to create data source objects of arbitrary types from XAML.

11 XML datový zdroj WPF má přímou podporu pro XML datový zdroj
Uložen externě v souboru Nebo jako objekt XML dokumentu v paměti XPath výraz pro výběr hodnoty <Auta> <Auto Typ="Skoda" Model="Roomster"> <Image>roomster.png</Image> </Auto> <Auto> ... </Auto> </Auta> auta.xml <XmlDataProvider x:Key="bouraky" XPath="/Auta/Auto" Source="auta.xml" /> WPF supplies an XmlDataProvider element, which allows you to use XML content as a source of data. Here we are using a file ‘cars.xml’. This XML file could be built into the application as an embedded resource stream, or you could also load it from some external source. (And you can load XML data in the codebehind too.) The XmlDataProvider also lets you put XML as a data island directly into the XAML. Data binding uses XPath to choose the items of data from an XML source. Note that the binding here sets the XPath property rather than the Path as we’ve used before. The XPath on the Binding will be evaluated relative to the result of the XPath expression of the XmlDataProvider. (If there is no XPath property set on the XmlDataProvider, then the bindings will just evaluate their XPath expressions relative to the root of the XML document.) <TextBlock TextContent="{Binding Source={StaticResource bouraky}}" />

12 Video ukázka Objektový datový zdroj, XML datový zdroj
Demo II: different data models XmlBinding

13 Kolekce jako zdroj Zdroj může být představován i kolekcí objektů
Zobrazení ve formě iterace po jednotlivých položkách kolekce nebo připojení k objektu ItemsControl (ListBox, ListView, TreeView) ItemControl podporuje pouze OneWay binding Realizace kolekce Měla by implementovat INotifyCollectionChanged Nebo použít třídu ObservableCollection<T> Každý objekt v kolekci by měl implementovat INotifyPropertyChanged

14 Práce se členy kolekce Přístup k jednotlivým položkám pomocí CollectionView „Sedí nad daty“ a poskytuje služby Iterace (MoveCurrentToNext, MoveCurrentToPrevious, …) Třídění podle více kritérií Filtrování Atribut IsSynchnizedWithCurrentItem zajistí zobrazení vybrané položky (např. ListBoxu) v detailním pohledu na data

15 Datová šablona Datová šablona prezentuje informace datového zdroje konkrétního typu Často použita pro položky kolekce class Car { string Image {get;set;} string Model {get;set;} } <DataTemplate x:Key="carTemplate"> <Border BorderBrush="Blue" BorderThickness="2" Background="LightGray"> <StackPanel> <Image HorizontalAlignment="Center" Source="{Binding Path=Image}" /> <Border HorizontalAlignment="Center" BorderBrush="Navy"> <TextBlock FontSize="18" Text="{Binding Path=Model}" /> </Border> </StackPanel> </DataTemplate> A data template defines how to present the information from a data source of a particular type. A template usually lives in a resource dictionary, and is simply a chunk of markup with {Binding} expressions. When a control presents data using a data template, it is as though the template is copied into that control, and its DataContext set to the data source. (This means that none of the binding expressions need to specify a source – they can just assume that the source will be an instance of the type the template is designed to present.)

16 Výběr Data Template Podle jména (resource dictionary key) Podle typu
ContentTemplate/ItemTemplate= {StaticResource maSablona} Podle typu <DataTemplate DataType="{x:Type local:Auto}"> <DataTemplate DataType="Book"> pro XML Of course data binding needs some way of determining which data template it should use. The most straightforward is to use the ContentTemplate or ItemTemplate property on the ContentControl or ItemsControl respectively. These let you specify exactly which data template the control should use, and you would normally use a StaticResource reference to point it at a template in a resource dictionary. If you need to present the same data in the same way in various different places in your UI, it could get tedious specifying the template explicitly on every control that uses it. So it is also possible to associate a data template with a type. If you set the template’s DataType property instead of giving it a name with x:Key, the template will automatically be applied anywhere the type is used. (The full scope of the template depends on the resource dictionary. If you put a data template in the Application.Resources dictionary, and specify a DataType, it will be applied anywhere, unless individual elements override it by specifying a different template. If you put it in some UI element’s Resources, it will be applied to that element and all its descendents.) If you are using XML data, then instead of setting the DataType to refer to a .NET type, you set it to an XML element name.

17 Video ukázka Kolekce jako zdroj dat, šablona pro položku kolekce
Photo Demo

18 Master-Detail vazba Jako master použijeme libovolný ItemsControl (např. ListBox) Musí mít nastaven IsSynchronizedWithCurrentItem="True" Umožňuje i víceúrovňový Master-detail scénář Master Detail class Oblast { string Nazev {get;set;} string Vino {get;set;} } Oblast .Nazev .Vino Vino .Odruda .Rocnik .Hodnoceni Master/details binding, where a list control selects the current item, and other controls show the details for the current item, is easily achieved. Simply set IsSynchronizedWithCurrentItem to True in the master. All Selector-derived classes support this, i.e. ListBox, ComboBox, TabControl, ListView. Any singular (non-list) controls bound to the same source will now follow the master. Also, any other list controls with IsSynchronizedWithCurrentItem set to true with the same source will also follow. (I.e. multiple list controls can also be kept in sync.) Oblast .Nazev .Vino class Vino { string Odruda {get;set;} string Rocnik {get;set;} string Hodnoceni {get;set;} } Vino .Odruda .Rocnik .Hodnoceni

19 Video ukázka Více úrovňová master-detail aplikace
RSS Browser

20 Shrnutí WPF rozumí vašim datům
Používejte své oblíbené datové modely: XML, objekty, SQL, WS … Připojte je k ovládacím prvkům

21 Odkazy Prezentace David Krčmář, Acad. Developer Evangelist
Video David Krčmář MSDN Windows Vista Developer Center Microsoft .NET Framework 3.0 Download platformy a ovládacích prvků Doporučení pro Windows Vista UX Další odkazy

22 © 2009 Microsoft Corporation.


Stáhnout ppt "Windows Presentation Foundation Data Binding"

Podobné prezentace


Reklamy Google