Arthur Zaczek Nov 2014
1 WPF 1.1 WPF Windows Presentation Foundation, seit.net 3.0 Introduction to WPF: http://msdn.microsoft.com/en-us/library/aa970268(v=vs.110).aspx Windows Presentation Foundation: http://msdn.microsoft.com/en-us/library/ms754130(v=vs.110).aspx 1.2 XAML Extensible Application Markup Language Im XAML wird das Aussehen definiert, im Code die Logik Es kann auch das Aussehen im Code definiert werden Code-Behind enthält die Logik Mit MVVM ist es nicht notwendig im Code-Behind Logik zu implementieren 1.3 XAML <Window x:class="wpf.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:ctrls="clr-namespace:wpf.controls" Title="SWE 2 - Wpf Samples"> <ScrollViewer> <ItemsControl ItemsSource="{Binding Commands"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Columns="2" IsItemsHost="True" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate DataType="vmdl:CommandViewModel"> <ctrls:commandbutton CommandViewModel="{Binding" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </ScrollViewer> </Window> 1.4 XAML - Layouts Controls werden mit Hilfe von Layouts positioniert: Border Canvas DockPanel Expander Grid GroupBox ScrollViewer StackPanel 1
1.5 XAML - Controls Einige WPF-Controls: <TextBlock Text="TextBlock" /> <TextBox Text="TextBox" /> <ComboBox /> <CheckBox>Checkbox</CheckBox> <RadioButton>RadioButton</RadioButton> <Button>Button</Button> 1.6 DataBinding DataBinding verknüpft Daten mit Controls Controls mit Daten Controls mit Controls Erfolg deklarativ im XAML, auch im Code möglich Benachrichtigungen über INotifyPropertyChanged oder DependenyProperties (siehe nächste Folien) Data Binding Overview: http://msdn.microsoft.com/en-us/library/ms752347(v=vs.110).aspx 1.7 DataBinding <TextBlock Margin="10" Text="{Binding Text" /> <TextBox Margin="10" Text="{Binding Text, UpdateSourceTrigger=PropertyChanged" /> <ListView ItemsSource="{Binding Values" VerticalContentAlignment="Center" BorderThickness="0"> <ListView.ItemTemplate> <DataTemplate> <DockPanel> <CheckBox DockPanel.Dock="Left" IsChecked="{Binding IsChecked, Mode=OneWay" /> <TextBlock Text="{Binding Text, Mode=OneWay" Margin="5,0,0,0" /> </DockPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> 1.8 DataContext DataContext ist die Datenquelle für Binding Wird an geeigneter Stelle gesetzt Meistens am Root-Element im CodeBehind oder vom Aufrufer 2
Wird in der Hierarchie nach unten vererbt Bis er ersetzt wird, z.b. bei Listen für jedes Listenelement DataContext Property: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext(v= 1.9 DataContext public partial class EditPersonWindow : Window { public EditPersonWindow(PersonViewModel vmdl) { InitializeComponent(); this.datacontext = vmdl; 1.10 INotifyPropertyChanged Benachrichtigung über Veränderungen einzelner Properties UI kann neu gezeichnet werden Binding kann neu ausgewertet werden Objekt muss INotifyPropertyChanged implementieren INotifyPropertyChanged: http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychange 1.11 INotifyPropertyChanged Typische INotifyPropertyChanged Implementierung: private string _text; public string Text { get { return _text; set { if (_text!= value) { _text = value; OnPropertyChanged("Text"); OnPropertyChanged("DisplayText"); // also notify another property public string DisplayText { get { return string.format("{0: {1", ID, Text); 3
1.12 DependencyProperties Storage wird zur Verfügung gestellt Benachrichtigungen werden automatisch zur Verfügung gestellt Objekt muss von DependencyObject ableiten DependencyProperties: http://msdn.microsoft.com/en-us/library/ms752914(v=vs.110).aspx 1.13 DependencyProperties Typische DependencyProperty Implementierung: public string TextDP { get { return (string)getvalue(textdpproperty); set { SetValue(TextDPProperty, value); // Using a DependencyProperty as the backing store for TextDP. // This enables animation, styling, binding, etc... public static readonly DependencyProperty TextDPProperty = DependencyProperty.Register("TextDP", typeof(string), typeof(databindingviewmodel), new PropertyMetadata("Simple text binding with Dependency Property")); Es gibt ein Codesnippet, welches eine DP erzeugen kann: propdp 2 MVVM, ViewModels 2.1 MVVM Model View ViewModel/ PresentationModel Die Daten, die dargestellt werden sollen Die Darstellung an sich Vermittler zwischen Model & View Siehe auch MVVM Folien 2.2 MVVM wer kennt wen 2.3 Model Repräsentation der Daten NUR DATEN, keine View-Logik, etc. Max. ein ToString für s Debuggen 4
Figure 1: MVVM Bildet die Struktur nach der Anwendungsdomäne ab Kennt niemanden (außer vielleicht BL) 2.4 ViewModel Transformiert ein Model in eine Anzeigbare form Berücksichtigt die Gegebenheiten auf einer UI Stellt weitere Eigenschaften & Methoden, die für die Anzeige benötigt werden zur Verfügung URL auf eine Flagge Anzahl der Elemente in einer Liste Mögliche Aktionen etc. Kennt das Model 2.5 View Die Ansicht, UI Daten werden aus dem ViewModel, nie aus dem Model dargestellt Aktionen/Methoden werden im ViewModel aufgerufen Kennt das ViewModel Mehrere Views können das selbe ViewModel benutzen SimpleView DetailsView 3 Weitere WPF-Themen 3.1 Converter Passen Werte aus ViewModellen an Anwendungen Boolean invertieren Pfade -> Icons Visibility anpassen IValueConverter : http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter(v=vs.110).aspx Walkthrough: http://msdn.microsoft.com/en-us/library/bb546926(v=vs.90).aspx 5
3.2 Converter <CheckBox IsChecked="{Binding Bool">Checked by User</CheckBox> <CheckBox IsChecked="{Binding Bool, Converter={StaticResource InvertedBoolConverter" Margin="10">Inverted</CheckBox> [ValueConversion(typeof(bool), typeof(bool))] public class InvertedBoolConverter : IValueConverter { public object Convert(object value, Type targettype, object parameter, System.Globalization.CultureInfo culture) { return value!= null?!(bool?)value : null; 3.3 Commands Commanding is an input mechanism in Windows Presentation Foundation (WPF) which provides input handling at a more semantic level than device input. Examples of commands are the Copy, Cut, and Paste operations found on many applications Commanding Overview: http://msdn.microsoft.com/en-us/library/ms752308(v=vs.110).aspx 3.4 Commands <DockPanel> <Menu DockPanel.Dock="Top"> <MenuItem Command="ApplicationCommands.Copy" /> <MenuItem Command="ApplicationCommands.Paste" /> </Menu> <Label DockPanel.Dock="Top">Text:</Label> <TextBox DockPanel.Dock="Top" /> </DockPanel> 3.5 Routed Commands WPF-routed commands give you a specific mechanism for hooking up UI controls such as toolbar buttons and menu items to handlers without introducing a lot of tight coupling and repetitive code into your application. Routed commands give you three main things on top of normal event handling: Routed Commands: http://msdn.microsoft.com/en-us/magazine/cc785480.aspx 3.6 Routed Commands <StackPanel> <!-- This checkbox enables both buttons --> 6
<CheckBox IsChecked="{Binding EnableMyCommand">Enable Command</CheckBox> <Button Command="{Binding MyCommand">My Command</Button> <!-- Custom command button control --> <ctrls:commandbutton CommandViewModel="{Binding MyCommand" /> </StackPanel> MyCommand = new SimpleCommandViewModel( "My Command", "My command in this sample application", () => { MessageBox.Show("Hello from my command", "Hello!");, () => EnableMyCommand); 3.7 Commands Anwendung: Commands in Abhänigkeit von Zuständen aktivieren/deaktivieren Commands wiederverwenden Erweiterung: Smart Routed Commands http://www.codeproject.com/articles/21166/smart-routed-commands-in-wpf 3.8 Content-/ItemTemplate Jedes Control hat grundsätzlich kein Aussehen Das Aussehen wird durch Templates definiert Es gibt für jedes Control ein Standard Template Abhängig vom Betriebssystem-Style Sie können auch eigene Templates definieren Styles and Templates: http://msdn.microsoft.com/en-us/library/bb613570(v=vs.110).aspx ControlTemplate: http://msdn.microsoft.com/en-us/library/ee230084(v=vs.110).aspx 3.9 Content-/ItemTemplate <Button>This is a default button</button> <Button> <StackPanel> <TextBlock Text="Button with additional control" /> <CheckBox>Checkbox</CheckBox> </StackPanel> </Button> <Button> <Button.Template> <ControlTemplate> <Grid> <Ellipse x:name="border" Fill="DarkGray" Stroke="Black" /> 7
<TextBlock x:name="text" Foreground="White" Text="Play" FontSize="25" /> </Grid> </ControlTemplate> </Button.Template> </Button> 3.10 Content-/ItemTemplate Figure 2: Content-/ItemTemplate 3.11 DataTemplate Für jeden Datentyp in einer können Sie ein eigenes Template definieren Data Templating Overview: http://msdn.microsoft.com/en-us/library/ms742521(v=vs.110).aspx 3.12 DataTemplate <DataTemplate DataType="{x:Type vmdlsamples:catviewmodel"> <DockPanel> <Image DockPanel.Dock="Left" Source="/Wpf;component/Images/cat.jpg" /> 8
<TextBlock Margin="10,0,0,0" Text="{Binding Name" /> </DockPanel> </DataTemplate> <DataTemplate DataType="{x:Type vmdlsamples:dogviewmodel"> <DockPanel> <TextBlock Text="{Binding Name" FontWeight="Light" FontSize="20"/> </DockPanel> </DataTemplate> 3.13 DataTemplate Figure 3: DataTemplate 3.14 Styles Mit Styles können Eigenschaften von Controls angepasst werden http://msdn.microsoft.com/en-us/library/ms745683(v=vs.110).aspx Sie sind einerseits mächtig in ihren Möglichkeiten, andererseits nicht so flexibel wie CSS Pro Control kann nur ein Style definiert werden Leichte Abhilfe schafft Vererbung 9
3.15 Styles <StackPanel> <StackPanel.Resources> <Style x:key="heading" TargetType="TextBlock"> <Setter Property="FontFamily" Value="Segoe UI"/> <Setter Property="FontSize" Value="30"/> </Style> <Style x:key="wrapwithoutbase" TargetType="TextBlock"> <Setter Property="TextWrapping" Value="Wrap"/> </Style> <Style x:key="wrap" TargetType="TextBlock" BasedOn="{StaticResource BaseTextBlock"> <Setter Property="TextWrapping" Value="Wrap"/> </Style> </StackPanel.Resources> <TextBlock Style="{StaticResource Heading" Text="..." /> <TextBlock Style="{StaticResource Wrap" Text="..." /> <TextBlock Style="{StaticResource WrapWithoutBase" Text="..." /> </StackPanel> 3.16 Trigger Mit Trigger können Eigenschaften eines Controls aufgrund von anderen Eigenschaften geändert werden. Beispiel: IsMouseOver -> Hintergrundfarbe ändern Trigger: http://msdn.microsoft.com/en-us/library/ms745683(v=vs.110).aspx#styling_triggers 3.17 Trigger <Style x:key="heading" TargetType="TextBlock"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Background" Value="LightYellow" /> </Trigger> </Style.Triggers> </Style> 3.18 Resources Styles, Templates und uvm. können in ResourceDictionaries definiert und wieder verwendet werden Performanceunterschiede zwischen Dynamic & StaticResources Resources: http://msdn.microsoft.com/en-us/library/ms742538(v=vs.110).aspx 3.19 User-/CustomControls Mit beiden werden wiederverwendbare Controls implementiert Es sind Klassen, daher können sie im XAML wie gewöhnliche Controls angeschrieben werden. 10
UserControl: Xaml + CodeBehind Einfach, wie ein gewöhnliches Fenster zu implementieren Langsam im Instanziieren CustomContrl: C# Klasse + Template Etwas Aufwändiger Schnell im Instanziieren 11