Charles Petzold www.charlespetzold.com Controls and Data Binding.

Slides:



Advertisements
Similar presentations
Computers: Tools for an Information Age Writing Your Own Web Page: Using HTML and Web Authoring Tools.
Advertisements

Chapter 3 – Web Design Tables & Page Layout
Developing HTML5 Application using MVVM pattern Pekka Ylenius.
Intermediate Level Course. Text Format The text styles, bold, italics, underlining, superscript and subscript, can be easily added to selected text. Text.
Dinko Jakovljević Microsoft Student Partner | BambooLab
1 Chapter 12 Working With Access 2000 on the Internet.
Web Development Using ASP.NET CA – 240 Kashif Jalal Welcome to week – 3-1 of…
Real world Windows Phone development Igor
Building Silverlight Applications Using the MVVM pattern An Introduction by Peter Messenger Senior Developer – Qmastor
1 Agenda Overview Review Roles Lists Libraries Columns.
With Alex Conger – President of Webmajik.com FrontPage 2002 Level I (Intro & Training) FrontPage 2002 Level I (Intro & Training)
Creating a Web Page HTML, FrontPage, Word, Composer.
Tutorial: Introduction to ASP.NET Internet Technologies and Web Application 4 th February 2010.
Chapter 3 Dreamweaver: Part I The Web Warrior Guide to Web Design Technologies.
.NET Database Technologies: Introduction to WPF and Entity Framework DataBinding.
Overview of Previous Lesson(s) Over View  ASP.NET Pages  Modular in nature and divided into the core sections  Page directives  Code Section  Page.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
Introduction to Mobile Programming. Slide 2 Overview Fundamentally, it all works the same way You get the SDK for the device (Droid, Windows, Apple) You.
1 Intro XAML Attribute syntax & property syntax Panels Reusable resources Controls Data binding Steen Jensen, spring 2014.
An Introduction to Silverlight Matt Harrington Developer Evangelist, Microsoft October 20, 2011.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
ASP.NET Web Server Controls Basic Web Server Controls.
Tutorial 121 Creating a New Web Forms Page You will find that creating Web Forms is similar to creating traditional Windows applications in Visual Basic.
Windows Presentation Foundation Adam Calderon Principal Engineer Interknowlogy LLC
Adam Calderon – C# MVP Application Development Practice Lead Interknowlogy.
Domain 3 Understanding the Adobe Dreamweaver CS5 Interface.
Basic WPF Controls Doncho Minkov Telerik School Academy schoolacademy.telerik.com Technical Trainer
V 1.0 Programming III. Automatic notifications (…Changed, INofityPropertyChanged, ObservableCollection ) Data formatters Data conversions Resources.
JavaScript, Fourth Edition Chapter 5 Validating Form Data with JavaScript.
LAYOUT CONTROLS. XAML Overview XAML : eXtensible Application Markup Language pronounced (ZAMEL) is a markup language used to design user interfaces XML-based.
Object Oriented Software Development 9. Creating Graphical User Interfaces.
Windows Phone MVVM and Unit Testing Step by Step Andy Wigley Windows Phone Development MVP, Mobile Software Consultant APPA Mundi Ltd WPH208.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL Windows Presentation Foundation Ruwan Wijesinghe.
WaveMaker Visual AJAX Studio 4.0 Training Basics: Building Your First Application Designer Basics.
Adam Calderon – C# MVP Application Development Practice Lead Interknowlogy.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
Svetlin Nakov Telerik Corporation
Windows Presentation Foundation (WPF). Introduction Separates appearance of user interface from behavior Appearance usually specified by XAML Behavior.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
V 1.0 Programming III. Converters Resources. V 1.0ÓE-NIK, 2014 Converters Data conversion: –Can be automatic! E.g.: SolidColorBrush  string, int  string.
ControlTemplate and DataTemplate Doncho Minkov Telerik School Academy Technical Trainer
1 Catching up on Rich Clients (round 1) Mike Ormond, Mike Taulty Developer & Platform Group Microsoft Ltd
Module 4 Taking Control of the User Interface. Module Overview Sharing Logical Resources in an Application Creating Consistent User Interfaces by Using.
04 |Sharing Code Between Windows 8 and Windows Phone 8 in Visual Studio Ben Riga
V 1.0 Programming III. Automatic notifications with data binding (…Changed, INofityPropertyChanged, ObservableCollection, DataTemplate) Data formatters.
CPSC 481 – Week #7 Sowmya Somanath
Writing Your Own Web Page: Using HTML and FrontPage Chapter 10.
COMPUTER PROGRAMMING I 3.01 Apply Controls Associated With Visual Studio Form.
V 1.0 Programming III. XAML Data Binding I.. V 1.0ÓE-NIK, 2014 XAML namespaces Namespaces define the allowed tags and attributes The one without the prefix.
COMPUTER PROGRAMMING I 3.01 Apply Controls Associated With Visual Studio Form.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL Windows Presentation Foundation Ruwan Wijesinghe.
Windows 8 apps and the MVVM pattern SILVERLIGHTSHOW.NET WEBINARS SERIES GILL CLEEREN, October 16 th
Programming with MVVM Miguel A. Castro Architect -
COMP 143 Web Development with Adobe Dreamweaver CC.
Part of the Microsoft.NET Framework 3.0 Tomer Shamam.NET Technologies Expert Sela Group
COMPUTER PROGRAMMING I Apply Procedures to Develop List Box and Combo Box Objects.
Working in a Mobile App Development Environment Lesson 2.
Data Binding, Binding Properties Doncho Minkov Telerik School Academy Technical Trainer
Adam Schultz MVVM and WPF. MVVM Model, View, ViewModel A software architecture designed to separate out User Interface design, Business Logic, and Data.
Jim Fawcett, Brown Bag Seminar Series Fall 2007
In Windows 8 Store Applications
Real world Windows Phone development
Creating a Flash Web Site
Ben Riga 02 | Basics of View Models Ben Riga
Jim Fawcett, Brown Bag Seminar Series Fall 2007
An introduction to MVVM using WPF NISCHAL S
XAML Deep Dive for Windows & Windows Phone Apps Jump Start
Web Development Using ASP .NET
Visual C# - GUI and controls - 1
Windows Forms in Visual Studio 2005: An in-depth look at key features
Presentation transcript:

Charles Petzold Controls and Data Binding

Agenda Built-in controls Styles and templates Data binding Model-View-ViewModel (MVVM) Items controls The WebBrowser control Application bars Toolkit controls

SWP contains assortment of basic controls –TextBox and PasswordBox –Button, CheckBox, RadioButton, and HyperlinkButton –Slider and ProgressBar –MediaElement and MultiScaleImage –ListBox, Pivot, and Panorama –WebBrowser and other controls Touch support built in More in Silverlight for Windows Phone Toolkit Controls

Button Control <Button Width="400" Height="240" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Content="Click Me" Click="OnClick" /> private void OnClick(object sender, RoutedEventArgs e) {... }

Button with Custom Content

TextBox Control // XAML // C# string input = Input.Text; // What the user typed

SIP = Software Input Panel InputScope property of text-input elements permits SIP to be tailored to input type More than 60 input scopes available SIPs and Input Scopes InputScope="Default"InputScope="TelephoneNumber"

Specifying an Input Scope // Short form (XAML) // Long form (XAML with IntelliSense) // C# Input.InputScope = new InputScope() { Names = { new InputScopeName() { NameValue = "TelephoneNumber" } } };

Useful Input Scopes NameDescription Default Basic text entry (letters, numbers, and symbols) Text Text entry with auto-capitalization, auto-complete, and more Number Numeric data entry TelephoneNumber Phone number data entry SmtpAddress address data entry Url URL data entry

ProgressBar Control ProgressBar showing 40% completeIndeterminant ProgressBar

ProgressBar Performance // Never do this! // Do this instead... Progress.IsIndeterminant = true; // Operation begins... Progress.IsIndeterminant = false; // Operation completes

demo Control Basics

Allow look and feel to be factored from content –Provide level of indirection between visual properties and their values Style = Collection of property values –Define style as XAML resource –Apply style using {StaticResource} markup extension –Or apply it programmatically Global scope or local scope Styles

Defining a Global Style // App.xaml

Defining a Local Style // MainPage.xaml

Applying Styles Explicit property value overrides style property value

<Style x:Key="TranslucentButtonStyle" TargetType="Button" BasedOn="{StaticResource ButtonStyle}"> BasedOn Styles

demo Styles

Redefine a control’s entire visual tree –Perform deep customization while retaining basic behavior of control –Exposed through control's Template property Inherited from Control base class Use {TemplateBinding} to flow property values from control to template Use ContentPresenter and ItemsPresenter to flow content and items to template Control Templates

Elliptical Button <TextBlock FontSize="24" Text="Click Me" HorizontalAlignment="Center" VerticalAlignment="Center" />

<Button Width="256" Height="128" FontSize="24" Content="Click Me" Foreground="Black"> <Ellipse Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"> <TextBlock FontSize="24" Text="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" /> {TemplateBinding}

<Button Width="256" Height="128" FontSize="24" Content="Click Me" Foreground="Black"> <Ellipse Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" /> ContentPresenter

Combining Styles and Templates <Ellipse Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">

demo Control Templates

Permits properties of one object to be bound to properties of another –Target property must be DependencyProperty –Source property can be any type of property –Source can be a collection if target is items control OneTime, OneWay, and TwoWay bindings {Binding} markup extension provides declarative support for data binding Data Binding

Data Binding Schema Value Converter Value Converter Target Dependency Property Dependency Property Binding Object Binding Object Source Property Converts data format and optionally validates it in two- way data binding scenarios Provides data and optionally receives it (two-way binding) Consumes data and optionally sends it (two- way binding) Flows data between source and target

Creates Binding objects declaratively {Binding} TextBlock Text Property Text Property Binding Object Binding Object TextBox Text Property Text Property

Specifying the Data Source (1) // XAML // C# Output.DataContext = Input;

Specifying the Data Source (2) <TextBlock x:Name="Output" FontSize="36" Text="{Binding Text, ElementName=Input}" /> ElementName identifies another XAML element as the data source

Two-Way Data Binding <Slider Minimum="0" Maximum="100" Value="{Binding Text, ElementName=Input, Mode=TwoWay}" /> Mode identifies the binding mode

Infrastructural interface used in data classes Notifies binding object when data changes Essential for one-way data binding! INotifyPropertyChanged Data Class Property INotifyPropertyChanged

Implementing INotifyPropertyChanged public class Person : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private decimal _salary; public decimal Salary { get { return _salary; } set { _salary = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Salary")); }

Infrastructural interface used in collection classes Notifies binding object when collection changes INotifyCollectionChanged Collection Class Item INotifyCollectionChanged IList ICollection IEnumerable

BCL collection class that implements INotifyCollectionChanged –System.Collections.ObjectModel namespace Fires CollectionChanged events when items are added or removed (or collection is refreshed) ObservableCollection // Ordinary collection List names = new List (); // Observable collection ObservableCollection names = new ObservableCollection ();

Objects that convert values involved in data binding from one type to another Implement IValueConverter –Convert – Convert from type A to type B –ConvertBack – Convert from type B to type A Specified with Converter attribute in {Binding} expression Value Converters

ImageConverter public class ImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { BitmapImage bi = new BitmapImage(); bi.SetSource(new MemoryStream((Byte[])value)); return bi; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); }

Using ImageConverter. <Image Source="{Binding ThumbnailImage, Converter={StaticResource ImageConverter}}" />

demo Data Binding

Controls that display collections of items Generally acquire items through data binding Data templates control how items are rendered Items Controls PivotListBox Panorama

ListBox Control // XAML <ListBox FontSize="{StaticResource PhoneFontSizeExtraLarge}" SelectionChanged="OnSelectionChanged"> // C# private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { int index = (sender as ListBox).SelectedIndex;... }

ListBox with Rich Content <TextBlock Text="Item One" Style="{StaticResource PhoneTextExtraLargeStyle}" /> <TextBlock Text="Convallis dapibus non ut justo" Style="{StaticResource PhoneTextAccentStyle}" />.

ListBox Data Binding // XAML <ListBox x:Name="List" FontSize="{StaticResource PhoneFontSizeExtraLarge}" /> // C# string[] items = { "Item One", "Item Two", "Item Three" }; List.ItemsSource = items;

ListBox Data Templates

Providing a Data Source ObservableCollection items = new ObservableCollection (); items.Add(new Item { Source = "Item.png", Title = "Item One", Description = "Convallis dapibus non ut justo" }); items.Add(new Item { Source = "Item.png", Title = "Item Two", Description = "Convallis dapibus non ut justo" }); items.Add(new Item { Source = "Item.png", Title = "Item Three", Description = "Convallis dapibus non ut justo" }); List.ItemsSource = items; public class Item { public string Source { get; set; } public string Title { get; set; } public string Description { get; set; } } public class Item { public string Source { get; set; } public string Title { get; set; } public string Description { get; set; } }

SelectedIndex gets and sets index of selected item –-1 means no item is currently selected SelectedItem property gets reference to item that is currently selected – with strong typing –null means no item is currently selected The SelectedItem Property // SelectedItem returns an Item reference because ListBox // is bound to collection of Item objects Item item = List.SelectedItem as Item; String title = item.Title; // e.g., "Item One"

Model-View-ViewModel Popular design pattern used by teams doing WPF, Silverlight, and phone development –Loose coupling; separation of concerns –Enhanced testability and "Blendability" –Based on Martin Fowler's Presentation Model pattern Devised in 2005 by Microsoft's John Gossman WP7 lacks rich MVVM support (commanding) MVVM

Model-View-ViewModel ModelViewModelView Control Property Model Class Model Class Model Class Model Class Model Class Model Class Data Binding

ViewModel Example public class ViewModel { public ObservableCollection Items { get; set; } public ViewModel() { Items = new ObservableCollection (); Items.Add(new Item { Source = "Item.png", Title = "Item One", Description = "..." }); Items.Add(new Item { Source = "Item.png", Title = "Item Two", Description = "..." }); Items.Add(new Item { Source = "Item.png", Title = "Item Three", Description = "..." }); }

Binding to a ViewModel <ListBox x:Name="List" ItemsSource="{Binding Items}" DataContext="{StaticResource ItemsViewModel}">...

demo ListBoxes, Data Binding, and MVVM

Pivot Control Functionally similar to Tab control Divides a page into navigable items (PivotItems) Implemented in Microsoft.Phone.Controls.dll

Declaring a Pivot Control

Gets and sets index of current PivotItem Can't be set until control fires Loaded event if control contains more than three PivotItems The SelectedIndex Property // Get SelectedIndex (works anywhere) int index = PivotControl.SelectedIndex; // Set SelectedIndex (works reliably only after Loaded event) PivotControl.SelectedIndex = 3;

demo Pivot Control

Panorama Control Divides page into navigable PanoramaItems Supports image background for magazine feel Implemented in Microsoft.Phone.Controls.dll

Declaring a Panorama Control

Panorama's SelectedIndex property is read-only Set SelectedIndex indirectly by setting DefaultItem The DefaultItem Property // Get SelectedIndex int index = PanoramaControl.SelectedIndex; // Force SelectedIndex by setting DefaultItem PanoramaControl.DefaultItem = PanoramaControl.Items[3];

demo Panorama Control

Displays live HTML content from URI or string –Source property downloads content –NavigateToString method injects content –IsScriptEnabled property controls script support Defaults to false; set to true to enable script InvokeScript method and ScriptNotify event facilitate communication between app and script Supports isolated storage as source of content –With support for relative URIs WebBrowser Control

Displaying Remote Content <phone:WebBrowser Source=" IsScriptEnabled="true" />

Inserting Content // XAML // C# private void OnWebBrowserLoaded(object sender, RoutedEventArgs e) { Browser.NavigateToString(" Hello, phone "); }

Add pages to project –Set build action to Content –URIs inside must be absolute Load pages with XNA's TitleContainer.OpenStream –Microsoft.Xna.Framework assembly Read content with StreamReader Pass content to WebBrowser control with NavigateToString Loading Local Pages

local.html URI must be absolute since origin is undefined

Loading local.html // XAML // C# private void OnWebBrowserLoaded(object sender, RoutedEventArgs e) { StreamReader reader = new StreamReader(TitleContainer.OpenStream("local.html")); Browser.NavigateToString(reader.ReadToEnd()); }

For local pages with relative links, store pages and resources they reference in isolated storage –Store entire sites on the phone –One usage scenario: HTML-based help systems Optionally use WebBrowser.Base property to specify base folder for relative links App must write pages to isolated storage –No tooling to help out WebBrowser and Isolated Storage

Isolated Storage Using Isolated Storage HelpMain Page1.html Page2.html Styles.css Pages can contain relative links to each other and to other resources Application Relative URI refers to resource in isolated storage

Invokes script functions in WebBrowser control –Don't forget IsScriptEnabled="true" Calls are synchronous WebBrowser.InvokeScript // C# string result = Browser.InvokeScript("toUpper", "Hello, phone").ToString(); // JavaScript function toUpper(text) { return text.toUpperCase(); // Returns "HELLO, PHONE" }

Event fired by WebBrowser control when script inside it calls window.external.notify WebBrowser.ScriptNotify // JavaScript window.external.notify('Ready'); // C# private void OnScriptNotify(object sender, NotifyEventArgs e) { MessageBox.Show(e.Value); // e.Value == "Ready" }

demo WebBrowser Control

Application Bars Quick, easy access to common tasks –Up to four buttons with hints/labels –Up to five menu items "Use icon buttons for the primary, most-used actions in the application. Do not use four icons just to use them. Less is more in this space."

Declaring an Application Bar <shell:ApplicationBarIconButton IconUri="/Icons/appbar.refresh.rest.png" Text="Refresh" Click="OnRefreshButtonClicked" /> <shell:ApplicationBarIconButton IconUri="/Icons/appbar.settings.rest.png" Text="Settings" Click="OnSettingsButtonClicked" />

Processing Button Clicks void OnRefreshButtonClicked(object sender, EventArgs e) { // TODO: Respond to Refresh button } void OnSettingsButtonClicked(object sender, EventArgs e) { // TODO: Respond to Settings button }

Disabling Buttons in Code // XAML <shell:ApplicationBarIconButton x:Name="RefreshButton" IconUri="/Icons/appbar.refresh.rest.png" Text="Refresh" Click="OnRefreshButtonClicked" /> // This throws a NullReferenceException RefreshButton.IsEnabled = false; // This doesn't (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = false;

Application Bar Icons 32 stock icons provided in WP7 SDK –\Program Files\Microsoft SDKs\Windows Phone\v7.0\Icons\dark Use "dark" icons only in application bars Set Build Action to "Content" in Visual Studio RefreshNewDelete Save PlayPauseSettingsDownload

Custom Application Bar Icons Icon must be 48 x 48 pixels Icon must have a transparent background Icon foreground must be white –Allows OS to colorize based on selected theme ustom_applicationbar_icon.htm

demo Application Bars

Silverlight for Windows Phone Toolkit contains additional controls –Source code –Binaries –Samples com/releases/view/55034 Toolkit Controls

Using the ToggleSwitch Control // XAML // C# private void OnClick(object sender, RoutedEventArgs e) { if ((bool)(sender as ToggleSwitch).IsChecked) MessageBox.Show("On"); else MessageBox.Show("Off"); }

Using the DatePicker Control // XAML // C# private void OnValueChanged(object sender, DateTimeValueChangedEventArgs e) { MessageBox.Show(e.NewDateTime.ToString()); } You provide these icons; DatePicker provides the application bar and buttons

Charles Petzold Questions?