Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
388,43 KB
Nội dung
ptg this.ManagerTextBlock.SetBinding( TextBlock.TextProperty, new Binding("Manager") ); } DataContext Inheritance In the previous example, the MainPage constructor set the DataContext property, whereas its child TextBlock elements specified the binding. This usage pattern works because the DataContext property is an inherited property, that is, Silverlight determines the value of the property by finding the nearest parent element with the property explicitly set. You can reset a binding object connection by either calling the ClearValue method for the property or by setting the property to some other explicit value. Technical Insight Silverlight only provides built-in markup extensions; you cannot define your own. Future Silverlight versions will likely let you write your own markup extensions. The most general form of a markup extension is syntax for cre- ating an object and providing that object with a FrameworkElement instance and the DependencyProperty to set. Technical Insight Silverlight freezes a binding object when you set the binding to a property, and you will no longer be able to modify the binding properties. Chapter 10: Data Binding 218 DEBUGGING TIP Errors in binding connections do not throw exceptions by default. To determine why a connection has failed, you can view the error mes- sages in your debugger output window. Later in this chapter, you will learn how to enable data-binding exceptions. From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg Data Synchronization and Binding Modes After establishing a binding between a data object and an element property, you may need to synchronize data values when the data object properties change or if the element property changes. For example, if the data that is bound to a control changes, the binding needs to notify the control to update its displayed value. If a control value changes, the binding may need to write the data back to a data store. To use data binding to synchronize your data with an element property, first ensure that your data object implements INotifyPropertyChanged : public class MyDataItem : INotifyPropertyChanged { // // Set a default value in the constructor // public MyDataItem() { this.employee = ""; } // // INotifyPropertyChanged implementation // public event PropertyChangedEventHandler PropertyChanged; // // Employee property // public string Employee { get { return this.employee; } set { this.employee = value; // Call the PropertyChanged handler if (PropertyChanged != null) Data Binding Objects 219 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg { PropertyChanged(this, new PropertyChangedEventA rgs("Employee")); } } } private String employee; } To control how properties synchronize, you can set the binding mode of a Binding object to OneTime , OneWay , or TwoWay . OneTime indicates that Silverlight will read the data only once and will never update values when properties are changed. OneWay indicates that changes to a data object will change the element property, but changes to the element property will not change the data object. With a OneWay binding, changes to the element properties will disconnect the Binding object and will no longer synchro- nize data. TwoWay indicates that Silverlight will synchronize changes to the element property with the data object and changes to the data object with the element. The default binding mode is OneWay . You can specify the binding mode by setting the Mode property on a Binding object, or declaratively through the markup extension: <UserControl x:Class="BindingModeExample.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <StackPanel> <TextBlock x:Name="myOneTimeTextBlock" Text="{Binding Employee, Mode=OneTime}" /> <TextBlock x:Name="myOneWayTextBlock" Text="{Binding Employee, Mode=OneWay}" /> <TextBlock x:Name="myTwoWayTextBlock" Text="{Binding Employee, Mode=TwoWay}" /> Chapter 10: Data Binding 220 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg </StackPanel> </UserControl> Changes to MyDataItem or TextBlock properties then synchronize based on the binding mode: MyDataItem dataItem = new MyDataItem(); this.DataContext = dataItem; // Updates only the TextBlocks set to bind mode // OneWay and TwoWay. Does not update the OneTime // binding mode TextBlock. dataItem.Employee = "Mark B"; // Does not update the data source since only OneWay // binding is specified // // Setting the local value also removes the binding // associated with this property this.myOneWayTextBlock.Text = "Mark C"; // Updates the data source since TwoWay binding // is specified this.myTwoWayTextBlock.Text = "Mark D"; Data Binding Collections with ItemsControl In Chapter 9, “Controls,” you learned how to use an ItemsControl element. In this section, you learn how to bind data to your ItemsControl . To bind to a list, follow these steps: 1. Provide a data source that is a collection of some object type. For proper synchronization, make sure your data source properly implements INotifyCollectionChanged . 2. Use an ItemsControl element as the display container for your list. 3. Create a DataTemplate to specify the display of each item. A DataTemplate is an ItemTemplate that you have already seen in Chapter 9. Data Binding Objects 221 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg 4. Set the ItemsSource property of the ItemsControl to the collection of data to display as described in Chapter 9. To implement a collection-based data source, it is simplest to inherit from ObservableCollection: public class MyDataCollection : ObservableCollection<String> { public MyDataCollection() { // // Populate the data source with some data // this.A dd("Item 1"); this.A dd("Item 2"); this.A dd("Item 3"); } } The next step is to create an ItemsControl ( or any ItemsControl derived control such as a ListBox ) as shown in Figure 10.2. Chapter 10: Data Binding 222 Figure 10.2: Data binding to a list <UserControl x:Class="ItemsControlExample.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <ItemsControl x:Name="myItemsControl"> <ItemsControl.ItemTemplate> <DataTemplate> <Border BorderThickness="2" BorderBrush="Black" CornerRadius="3"> <TextBlock Text="{Binding}"/> </Border> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </UserControl> From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg In the previous data-template example, the Text property was set to {Binding} without specifying a property to bind. The reason no addi- tional parameters were required was because our collection was of type String , and you are binding the object itself (not a sub-property) to the Text property. If the collection was of a type that contains multiple prop- erties, use the same binding syntax used in the previous sections that specified the property name. The ItemsControl sets the DataContext to the list when you set the ItemsSource property, and in this case, the bind- ing refers to the item types. As you learned in Chapter 9, the default behavior for an ItemsControl is to create a StackPanel that replaces the content contained within a DataTemplate specified in the ItemTemplate property. For example, in this case, you get the equivalent of the following XAML shown in Figure 10.2: <StackPanel> <Border BorderThickness="2" BorderBrush="Black" CornerRadius="3"> <TextBlock Text="Item 1"/> </Border> <Border BorderThickness="2" BorderBrush="Black" CornerRadius="3"> <TextBlock Text="Item 2"/> </Border> <Border BorderThickness="2" BorderBrush="Black" CornerRadius="3"> <TextBlock Text="Item 3"/> </Border> </StackPanel> Now that you have learned how to data bind to an ItemsControl class, you can use the same method to bind to any list-based class that derives from ItemsControl . For example, you can replace the ItemsControl container with a ComboBox to get the result shown in Figure 10.3. Data Binding Objects 223 Figure 10.3: Data binding to a ComboBox From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg <UserControl x:Class="ItemsControlExample.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <ComboBox x:Name="myItemsControl"> <ItemsControl.ItemTemplate> <DataTemplate> <Border BorderThickness="2" BorderBrush="Black" CornerRadius="3"> <TextBlock Text="{Binding}"/> </Border> </DataTemplate> </ItemsControl.ItemTemplate> </ComboBox> </UserControl> Chapter 10: Data Binding 224 PERFORMANCE TIP If your data source contains a list of items that are far greater than what Silverlight can display on the screen, the ItemsControl approach shown here generates many invisible elements and slows down the performance of your application. You should filter your ItemsSource to a collection containing only those items that are visible on the screen to improve performance. You can approximate the scroll thumb size for large lists based on typical item sizes. The ListBox element in Silverlight 3 will now virtualize large lists of data for you, and is much faster than using the ItemsControl element directly. PERFORMANCE TIP For best performance, keep your DataTemplate simple for large lists. Silverlight replicates the content you put in the DataTemplate for each item in your collection. A simpler DataTemplate decreases the load time of your content. As with the ItemsControl class, you can create custom controls with template customization by either using an ItemsControl for list-based con- trols or using the ContentControl element and ContentPresenter element for single item content controls. Chapter 9 discussed the ContentControl element and ContentPresenter element in detail. From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg Value Converters In the previous examples, we mapped data items directly to property values. You may need to convert a data value from one type to another before mapping to a property value. In our previous example, suppose you had a priority associated with each data item. Furthermore, suppose you want all high priority values to display in red. First, extend the list item definition to include the Priority property: public enum Priority { Normal, High } public struct MyDataItem { public MyDataItem(String name, Priority priority) { this.name = name; this.priority = priority; } public String Name { get {return this.name;} } public Priority Priority { get { return this.priority; } } private String name; private Priority priority; } As with the previous example, build a data set: public class MyDataCollection : ObservableCollection<MyDataItem> { public MyDataCollection() { // // Populate the data source with some data // Data Binding Objects 225 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg this.A dd(new MyDataItem("Item 1", Priority.High)); this.A dd(new MyDataItem("Item 2", Priority.Normal)); this.A dd(new MyDataItem("Item 3", Priority.Normal)); } } Now, define a class that implements IValueConverter to convert from a Priority type to a Brush type: public class MyPriorityConverter : IValueConverter { public object Convert( object value, Type targetType, // Ignore target type and always return a brush object parameter, System.Globalization.CultureInfo culture ) { object result = null; // // Check for high priority items and mark red // if ((Priority)value == Priority.High) { return new SolidColorBrush(Colors.Red); } // // If we haven't converted to anything special, default to // black // return new SolidColorBrush(Colors.Black); } public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture ) { // Implement this callback for two way data binding throw new NotImplementedException(); } } Chapter 10: Data Binding 226 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ptg After you have defined your value converter, you can use it with your Binding : <UserControl x:Class="ValueConverterExample.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:app="clr-namespace:ValueConverterExample" > <ItemsControl x:Name="myItemsControl"> <ItemsControl.Resources> <app:MyPriorityConverter x:Key="myDataConverter"/> </ItemsControl.Resources> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}" Foreground="{Binding Priority, Converter={StaticResource myDataConverter}}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </UserControl> By default, if you do not specify a value converter and the types do not match, Silverlight does some conversions automatically when possible. For example, Silverlight can convert most types to a string automatically. Data Validation If your data source throws an exception or a built-in Silverlight converter throws an exception, Silverlight ignores these exceptions. In the case of the ItemsControl class, the items control omits that item from the list. You may want to show a visual indicator for malformed data so that your application user can correct that data. To receive these errors, set both the NotifyOnValidationError and ValidatesOnExceptions flags on the Binding to receive validation errors: <TextBlock Text="{Binding Name, NotifyOnValidationError=True, ValidatesOnExceptions=True}" /> Data Binding Objects 227 From the Library of Lee Bogdanoff Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... chapter will describe the following: • The Silverlight effect design principles • How to use built-in effects • How to define custom pixel-based effects • How Silverlight effects work “under the hood” Effect Principles The design principles of Silverlight effects include the following: • Good performance for real-time animation • Basic built-in effects Real-Time Speed Silverlight 3 introduces a pixel shader... in Chapter 3, “Graphics.” During the ItemsControl element measure call, Silverlight parses all data templates and objects are instantiated to reflect the data changes Silverlight defers the template expansion process so that it does not expand items that are not visible Where Are We? This chapter discussed the following: • The Silverlight data-binding design principles • How to connect and synchronize... change for an element with an effect, Silverlight draws the sub-tree into a separate surface In addition, the rasterization step does the following: 1 Applies a transform so that the contents of the sub-tree are positioned at 0,0 and without the inherited rotation Silverlight keeps scale transforms so that your effect renders at the proper resolution In particular, Silverlight tries to store only meaningful... get the most performance benefit This chapter describes the following: • The Silverlight GPU acceleration principles • How you can properly use GPU acceleration in your applications to get the maximum performance benefit • How Silverlight GPU acceleration works “under the hood” GPU Acceleration Principles The design goals of Silverlight GPU acceleration are as follows: • Achieve better performance for... Image Quality The goal of Silverlight GPU acceleration is to provide better speed while maintaining similar image quality to CPU-based rendering There are situations where there is a direct tradeoff between image quality and speed In these situations, Silverlight provides options for selecting the quality you would like to achieve For example, if you stretch a vector graphic with Silverlight GPU acceleration,... OpenGL2.x for the Mac with a compatible video card that meets the minimum Silverlight runtime requirements The video cards and drivers supported may change Enable GPU Acceleration To enable GPU acceleration, set the EnableGPUA cceleration flag to true in the HTML page hosting your Silverlight plug-in: . explicit value. Technical Insight Silverlight only provides built-in markup extensions; you cannot define your own. Future Silverlight versions will likely. converter and the types do not match, Silverlight does some conversions automatically when possible. For example, Silverlight can convert most types to