Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Charles Petzold www.charlespetzold.com Controls and Data Binding."— Presentation transcript:

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

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

3 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

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

5 Button with Custom Content

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

7 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"

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

9 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 EmailSmtpAddress E-mail address data entry Url URL data entry

10 ProgressBar Control ProgressBar showing 40% completeIndeterminant ProgressBar

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

12 demo Control Basics

13 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

14 Defining a Global Style // App.xaml

15 Defining a Local Style // MainPage.xaml

16 Applying Styles Explicit property value overrides style property value

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

18 demo Styles

19 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

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

21 <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}

22 <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

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

24 demo Control Templates

25 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

26 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

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

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

29 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

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

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

32 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")); }

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

34 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 ();

35 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

36 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(); }

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

38 demo Data Binding

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

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

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

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

43 ListBox Data Templates

44 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; } }

45 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"

46 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

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

48 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 = "..." }); }

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

50 demo ListBoxes, Data Binding, and MVVM

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

52 Declaring a Pivot Control

53 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;

54 demo Pivot Control

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

56 Declaring a Panorama Control

57 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];

58 demo Panorama Control

59 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

60 Displaying Remote Content <phone:WebBrowser Source="http://www.bing.com" IsScriptEnabled="true" />

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

62 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

63 local.html URI must be absolute since origin is undefined

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

65 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

66 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

67 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" }

68 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" }

69 demo WebBrowser Control

70 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."

71 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" />

72 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 }

73 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;

74 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

75 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 http://www.kirupa.com/windowsphone/creating_c ustom_applicationbar_icon.htm

76 demo Application Bars

77 Silverlight for Windows Phone Toolkit contains additional controls –Source code –Binaries –Samples http://silverlight.codeplex.- com/releases/view/55034 Toolkit Controls

78 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"); }

79 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

80 Charles Petzold www.charlespetzold.com Questions?


Download ppt "Charles Petzold www.charlespetzold.com Controls and Data Binding."

Similar presentations


Ads by Google