1 Rainer Stropek cubido business solutions gmbh Fesselspiele Data Binding in WPF und Silverlight.
-
Upload
kriemhilde-neubaum -
Category
Documents
-
view
110 -
download
5
Transcript of 1 Rainer Stropek cubido business solutions gmbh Fesselspiele Data Binding in WPF und Silverlight.
1
Rainer Stropekcubido business solutions gmbh
Fesselspiele
Data Binding in WPF und Silverlight
2
Ziele
Grundlagen von Data Binding in WPF und Silverlight
Erklärung von Data Binding Szenarien anhand von typischen Anwendungsfällen
Hinweise auf Unterschiede bei Data Binding zwischen WPF und Silverlight
Rainer Stropek, cubido business solutions gmbh
3
EINFACHES DATA BINDING MIT UND OHNE DEPENDENCY PROPERTIES
Beispiel 1
Rainer Stropek, cubido business solutions gmbh
4
Grundlagen
Rainer Stropek, cubido business solutions gmbh
public class Competitor{
public string FirstName { get; set; }
public string LastName { get; set; }}
.property instance string FirstName{ .get instance string
MyApp.Competitor::get_FirstName()
.set instance void
MyApp.Competitor::set_FirstName(string)}
5
Grundlagen
Erstellen eines Bindings {Binding…} Markup Extension Binding Klasse
{StaticResource…} Markup Extension zum Zugriff auf Ressourcen
Rainer Stropek, cubido business solutions gmbh
6
Einfaches Data Binding
Rainer Stropek, cubido business solutions gmbh
<Window.Resources><local:Competitor x:Key="MyCompetitor"
FirstName="Benjamin" LastName="Raich" />
</Window.Resources><StackPanel>
<TextBox Text="{Binding Source={StaticResource MyCompetitor}, Path=FirstName}"
x:Name="FirstNameTextBox" /><TextBox Text="{Binding Source={StaticResource MyCompetitor},
Path=LastName}" x:Name="LastNameTextBox" />
<StackPanel Orientation="Horizontal"><TextBlock Text="Competitor:" /><TextBlock Text="{Binding ElementName=FirstNameTextBox,
Path=Text}" /><TextBlock Text="{Binding ElementName=LastNameTextBox,
Path=Text}" /></StackPanel>
<StackPanel Orientation="Horizontal"><Button Click="Button_Click">Show Competitor</Button><Button Click="Button_Click_1">Change Competitor</Button>
</StackPanel></StackPanel>
7
Grundlagen
Rainer Stropek, cubido business solutions gmbh
8
Grundlagen
Rainer Stropek, cubido business solutions gmbh
Geschäftsobjekt
TextBox TextBlock
Hermann
Hermann HermannRainer
Rainer
Rainer
Text wird verändert
Geschäftsobjekt
TextBox TextBlock
Hermann
Hermann Hermann
Rainer
Text wird im Code
verändertÄnderung des Properties wird nicht erkannt!
9
Grundlagen
Lösungen des Problems: Dependency Property Implementieren von INotifyPropertyChanged
Rainer Stropek, cubido business solutions gmbh
10
Dependency Property
Rainer Stropek, cubido business solutions gmbh
public class Competitor : DependencyObject{
public string FirstName{
get { return (string)GetValue(FirstNameProperty); }set { SetValue(FirstNameProperty, value); }
}public static readonly DependencyProperty FirstNameProperty =
DependencyProperty.Register("FirstName", typeof(string),typeof(Competitor), new UIPropertyMetadata(String.Empty));
public string LastName{
get { return (string)GetValue(LastNameProperty); }set { SetValue(LastNameProperty, value); }
}public static readonly DependencyProperty LastNameProperty =
DependencyProperty.Register("LastName", typeof(string), typeof(Competitor), new UIPropertyMetadata(String.Empty));
}}
11
Grundlagen
Rainer Stropek, cubido business solutions gmbh
WPF übernimmt Verwaltung der Propertywerte
12
Grundlagen
Nahezu alle Properties in WPF sind als Dependency Properties implementiert
Rainer Stropek, cubido business solutions gmbh
13
Grundlagen
Rainer Stropek, cubido business solutions gmbh
15
Grundlagen
Rainer Stropek, cubido business solutions gmbh
16
Einfaches Data Binding
Rainer Stropek, cubido business solutions gmbh
<StackPanel><TextBox Text="{Binding Path=FirstName}" x:Name="FirstNameTextBox" /><TextBox Text="{Binding Path=LastName}" x:Name="LastNameTextBox" /><StackPanel Orientation="Horizontal">
<TextBlock Text="Competitor:" /><TextBlock Text="{Binding Path=FirstName}" /><TextBlock Text="{Binding Path=LastName}" />
</StackPanel><StackPanel Orientation="Horizontal">
<Button Click="Button_Click">Show Competitor</Button><Button Click="Button_Click_1">Change Competitor</Button>
</StackPanel></StackPanel>
public MyWindow(){
InitializeComponent();this.DataContext = new Competitor
{ FirstName = "Benjamin", LastName = "Raich" };}
Tipp: DataContext statt Source oder
ElementName!
17
DATA BINDING UND COLLECTIONS
Beispiel 2
Rainer Stropek, cubido business solutions gmbh
18
ItemsControl Klasse
Binden der Collection an das Property ItemsSource
Rainer Stropek, cubido business solutions gmbh
Tipp: Steuern Sie das Aussehen der einzelnen Items über ein
Data Template!
19
Binden an ItemsSource
Rainer Stropek, cubido business solutions gmbh
<ComboBox ItemsSource="{Binding}"><ComboBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:Competitor}"><StackPanel Orientation="Horizontal">
<TextBlock Text="Competitor:" /><TextBlock Text="{Binding Path=FirstName}" /><TextBlock Text="{Binding Path=LastName}" />
</StackPanel></DataTemplate>
</ComboBox.ItemTemplate></ComboBox>
public MyWindow(){
InitializeComponent();this.DataContext = new List<Competitor>() {
new Competitor() { FirstName = "Hermann", LastName = "Mayer" },
new Competitor() { FirstName = "Benjamin", LastName = "Raich" }
};}
Template Binding
20
Binden an ItemsSource
Rainer Stropek, cubido business solutions gmbh
<Window.Resources><DataTemplate DataType="{x:Type local:Competitor}">
<StackPanel Orientation="Horizontal"><TextBlock Text="Competitor:" /><TextBlock Text="{Binding
Path=FirstName}" /><TextBlock Text="{Binding
Path=LastName}" /></StackPanel>
</DataTemplate></Window.Resources><StackPanel>
…<ComboBox ItemsSource="{Binding}" /><ListBox ItemsSource="{Binding}" />…
</StackPanel> Tipp: Legen Sie Data Templates zentral in den Ressourcen ab
(Window.Resources oder App.xaml)ComboBox und
ListBox nutzen gleiches Template
21
Collection
Hermann, Mario
Binden an ItemsSource
Rainer Stropek, cubido business solutions gmbh
ListBox
Hermann
Hermann
Element wird im Code hinzugefügt
Änderung der Collection wird nicht erkannt!
public MyWindow(){
InitializeComponent();this.DataContext = new ObservableCollection<Competitor>() {
new Competitor() { FirstName = "Hermann", LastName = "Mayer" },
new Competitor() { FirstName = "Benjamin", LastName = "Raich" }
};}
Implementiert INotifyCollectionChanged
22
DATA BINDING UND LINQ(ENTITY FRAMEWORK)
Beispiel 3
Rainer Stropek, cubido business solutions gmbh
23
Beispielanwendung
Rainer Stropek, cubido business solutions gmbh
25
System.Data.Objects.DataClasses
Linq und Data Binding
Rainer Stropek, cubido business solutions gmbh
Competitor
EntityObject
StructuralObject INotifyPropertyChanged
Linq-Klassen sind für Nutzung mit Data Binding vorbereitet
28
Linq und Data Binding
Rainer Stropek, cubido business solutions gmbh
…<ComboBox Name="EventComboBox" ItemsSource="{Binding}" Grid.Column="0"
Grid.ColumnSpan="2" Grid.Row="0" Margin="0,0,0,10" />…
private SkiEventEntities Context { get; set; }
public Window1(){
InitializeComponent();
this.Context = new SkiEventEntities();this.DataContext = this.Context.Event.Include("Competitor").
OrderBy(e => e.EventName);}
Linq-Query wird direkt an ComboBox gebunden
Tipp: Immer Geschäftsobjekte binden, nie Umweg über Strings
gehen!
29
MASTER-DETAIL BINDINGSBeispiel 4
Rainer Stropek, cubido business solutions gmbh
30
Master-Detail Binding
Rainer Stropek, cubido business solutions gmbh
Selektion = Filter für untere Liste
Aktuelle Auswahl = Filter
32
Master-Detail Binding
Rainer Stropek, cubido business solutions gmbh
…<ComboBox Name="EventComboBox" ItemsSource="{Binding}" Grid.Column="0"
Grid.ColumnSpan="2" Grid.Row="0" Margin="0,0,0,10" IsSynchronizedWithCurrentItem="True" />
<ListBox Name="CompetitorListBox" ItemsSource="{Binding Path=Competitor}"Grid.Column="0" Grid.Row="1" Margin="0,0,10,0" IsSynchronizedWithCurrentItem="True" />
…
Tipp: Mit UpdateSourceTrigger Zeitpunkt der Aktualisierung des
Bindings steuern
{Binding …, UpdateSourceTrigger=PropertyChanged}
34
ÄNDERUNGEN IN DB ZURÜCKSCHREIBEN
Beispiel 5
Rainer Stropek, cubido business solutions gmbh
35
Master-Detail Binding
Rainer Stropek, cubido business solutions gmbh
…protected override void OnInitialized(EventArgs e){
base.OnInitialized(e);this.SaveButton.Click += new RoutedEventHandler(this.SaveButton_Click);…
}
private void SaveButton_Click(object sender, RoutedEventArgs e){
this.entities.SaveChanges();}…
Alles andere erledigt Data Binding!
36
CONVERTERBeispiel 6
Rainer Stropek, cubido business solutions gmbh
37
Formatieren oder Umwandeln von Daten im Binding
Rainer Stropek, cubido business solutions gmbh
Standardverhalten: ToString()
39
Converter
Rainer Stropek, cubido business solutions gmbh
…<TextBox Name="TotalTimeTextBox" Grid.Column="1" Grid.Row="7"
Text="{Binding Path=TotalTime, Mode=TwoWay, Converter={StaticResource TimeToStringConverter}}" />
…
public class TimeToStringConverter : IValueConverter{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { … }
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { … }
}
40
GÜLTIGKEITSPRÜFUNGENBeispiel 7
Rainer Stropek, cubido business solutions gmbh
42
Gültigkeitsprüfung
Rainer Stropek, cubido business solutions gmbh
…<TextBox Name="TotalTimeTextBox" Grid.Column="1" Grid.Row="7">
<TextBox.Text><Binding Path="TotalTime" Mode="TwoWay"
Converter="{StaticResource TimeToStringConverter}"><Binding.ValidationRules>
<ExceptionValidationRule /></Binding.ValidationRules>
</Binding></TextBox.Text>
</TextBox>…
public class TimeToStringConverter : ValidationRule, IValueConverter{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { … }
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { … }
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { … }
}
Tipp: Converter und Gültigkeitsprüfung in einer Klasse zusammenfassen
43
Gültigkeitsprüfung
Rainer Stropek, cubido business solutions gmbh
…<TextBox Name="TotalTimeTextBox" Grid.Column="1" Grid.Row="7">
<TextBox.Text><Binding Path="TotalTime" Mode="TwoWay"
Converter="{StaticResource TimeToStringConverter}"><Binding.ValidationRules>
<ExceptionValidationRule /></Binding.ValidationRules>
</Binding></TextBox.Text>
</TextBox>… …<TextBox Name="TotalTimeTextBox" Grid.Column="1" Grid.Row="7">
<TextBox.Text><Binding Path="TotalTime" Mode="TwoWay"
Converter="{StaticResource TimeToStringConverter}“ValidatesOnExceptions="True" />
</TextBox.Text></TextBox>…
…<TextBox Name="TotalTimeTextBox" Grid.Column="1" Grid.Row="7"
Text="{Binding Path=TotalTime, Mode=TwoWay, Converter={StaticResource TimeToStringConverter},ValidatesOnExceptions=True}" />
…
Tipp: Schreibweise kann drastisch
verkürzt werden!
44
Gültigkeitsprüfung
Rainer Stropek, cubido business solutions gmbh
Button bleibt trotz Validierungsfehler aktiv
45
Gültigkeitsprüfung
Rainer Stropek, cubido business solutions gmbh
…<Button Name="SaveButton" Content="Save" Grid.Column="0" Grid.ColumnSpan="2“
Grid.Row="2" Margin="0,10,0,0"><Button.IsEnabled>
<MultiBinding Converter="{StaticResource IsEnabledConverter}"><Binding ElementName="TotalTimeTextBox"
Path="(Validation.Errors).Count" /><!-- Here you can enter additional validations -->
</MultiBinding></Button.IsEnabled>
</Button>…
public class IsEnabledConverter : IMultiValueConverter{
public object Convert(object[] values, Type targetType, object parameter,System.Globalization.CultureInfo culture) { … }
public object[] ConvertBack(object value, Type[] targetTypes, object parameter,
System.Globalization.CultureInfo culture) { … }}
Tipp: Als Multi-Value Converter implementieren, um mehrere Quell-Controls zu unterstützen
46
DATA BINDING ÜBER CONTROL-GRENZEN HINWEG
Beispiel 8
Rainer Stropek, cubido business solutions gmbh
48
Data Binding und User Controls
Rainer Stropek, cubido business solutions gmbh
<Window x:Class="SkiResults.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SkiResults" Title="Window1" Height="500" Width="500">…
<local:Details x:Name="DetailsForm" Grid.Column="1" Grid.Row="1" DataContext="{Binding Path=Competitor}" />
</Window>
Tipp: Auch bei User Controls mit Data Context arbeiten; wird auch
in diesem Fall vererbt!
49
Data Binding Unterschiede Silverlight und WPF
Data Binding in Silverlight funktioniert grundsätzlich so wie in WPF
Viele Einschränkungen IsSynchronizedWithCurrentItem gibt es nicht
Dependency Properties alleine reichen nicht für automatisches Update; INotifyPropertyChanged muss implementiert werden
Viele, viele weitere Kleinigkeiten
Vorsicht mit der Performance!
Rainer Stropek, cubido business solutions gmbh
50
Was wir nicht behandelt haben…
Bindings in Control Templates
RelativeSource Bindings
Anpassung des Fehlerhinweises bei Validierung
Rainer Stropek, cubido business solutions gmbh
51
Lust auf mehr?
Bücher WPF und XAML
Programmierhandbuch
XAML Kurz & Schnell
Entwickler Akademie C# Fundamentals
C# 3.5 Upgrade
Datenorientierte Anwendungen mit WPF und Silverlight
Rainer Stropek, cubido business solutions gmbh
52
FRAGEN [email protected]
Vielen Dank für‘s Kommen!
Rainer Stropek, cubido business solutions gmbh