Data Binding

 

 

 

Data binding provides a simple way for Silverlight-based applications to display and interact with data. The way data is displayed is separated from the management of the data. A connection, or binding, between the UI and a data object allows data to flow between the two. When a binding is established and the data changes, the UI elements that are bound to the data can reflect changes automatically. Similarly, changes made by the user in a UI element can be reflected in the data object. For example, if the user edits the value in a TextBox, the underlying data value is automatically updated to reflect that change.

Some common binding scenarios include binding a ListBox to a list of headlines, an input form's TextBox to a customer data object, or an Image to the current user's photo.

This topic contains the following sections:

This topic uses simple code examples to illustrate data binding concepts. For more complex examples, see the topics listed at the end.

You can also accomplish many data binding tasks using Visual Studio 2010. For more information, see Data Binding in the Silverlight Designer.

 



Every binding must specify a source and a target. The following illustration shows the basic concepts of a binding. The source can be any CLR object, including the target element itself or other UI elements. If the target is in a data template, the source can be the UI element to which the template is applied.

The target can be any DependencyProperty of a FrameworkElement.

Starting with Silverlight 4, the target can also be a DependencyProperty of a DependencyObject in the following cases:

Starting with Silverlight 5, the target can also be the Value property of a Setter within a Style. For an example, see the Style class overview.

The binding engine gets information from the Binding object about the following:

For example, the Foreground property of a TextBox can be bound to a SolidColorBrush so that the color of the text can change based on the data. In this scenario, the Foreground property is the target, and the SolidColorBrush object is the source for the binding.

The following example shows how to bind the Foreground color of a TextBox to a SolidColorBrush in code and XAML. The binding source is a property of the MyColors class, which is described later in this topic.

/>
// Create an instance of the MyColors class // that implements INotifyPropertyChanged. MyColors textcolor = new MyColors(); // Brush1 is set to be a SolidColorBrush with the value Red. textcolor.Brush1 = new SolidColorBrush(Colors.Red); // Set the DataContext of the TextBox MyTextBox. MyTextBox.DataContext = textcolor;

相关文章:

  • 2021-08-25
  • 2021-05-19
  • 2021-11-08
  • 2021-10-02
  • 2021-04-20
  • 2021-08-17
猜你喜欢
  • 2022-12-23
  • 2022-01-31
  • 2021-08-21
  • 2022-12-23
  • 2021-10-01
  • 2021-08-15
相关资源
相似解决方案