Data Binding in Silverlight

Source: Internet
Author: User

Currently, we are mainly engaged in the development of Silverlight. In our spare time, we will conduct a systematic study on the features of Silverlight to deepen our understanding and grasp of Silverlight as a whole.

In Silverlight, Data Binding adopts three modes:

  • OneWay: The target attribute is updated when the source attribute is updated. [default binding mode]
  • TwoWay: when the source attribute is updated, the target attribute is updated, and the source attribute is updated.
  • OneTime: The target attribute is initialized by the source attribute and will not be associated later.

Three binding modes:

The data classes used in this article are as follows:

    [DataContract()]
public class Student
{
[DataMember()]
public string Name
{
get;
set;
}

[DataMember()]
public int Age
{
get;
set;
}
}

WebService:

    [ServiceContract(Namespace = "")]
[SilverlightFaultBehavior]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class StudentManager
{
[OperationContract]
public Student GetOneStudent()
{
return new Student()
{
Name = "zhangsan",
Age = 22
};
}

[OperationContract]
public List<Student> GetAllStudent()
{
List<Student> students = new List<Student>()
{
new Student(){Name = "One",Age = 22},
new Student(){Name = "Two",Age = 23},
new Student(){Name = "Three", Age = 22}
};

return students;
}
}

XAML:

<Grid x: Name = "LayoutRoot" Background = "White">
<Grid. ColumnDefinitions>
<ColumnDefinition Width = "100" type = "codeph" text = "/codeph"/>
<ColumnDefinition/>
</Grid. ColumnDefinitions>
<Grid. RowDefinitions>
<RowDefinition Height = "Auto"/>
<RowDefinition Height = "Auto"/>
<RowDefinition Height = "Auto"/>
<RowDefinition Height = "Auto"/>
</Grid. RowDefinitions>

<TextBlock Text = "name:" HorizontalAlignment = "Right"> </TextBlock>
<TextBox x: Name = "NameTxt" Text = "{Binding Name}" Width = "300" HorizontalAlignment = "Left" Grid. Column = "1"> </TextBox>
<TextBlock Text = "Age:" HorizontalAlignment = "Right" Grid. Row = "1"> </TextBlock>
<TextBox x: Name = "AgeTxt" Text = "{Binding Age}" Width = "300" Grid. row = "1" Grid. column = "1" HorizontalAlignment = "Left"> </TextBox>
<Button x: Name = "Submit" Content = "View data binding mode" Width = "150" Grid. row = "2" Grid. column = "1" HorizontalAlignment = "Left" Click = "Submit_Click"> </Button>
</Grid>

Data Binding uses the OneWay mode by default. The data objects in the memory will not change because of the data objects on the user interface.

XAML hidden code:

Public partial class MainPage: UserControl
{
Public MainPage ()
{
InitializeComponent ();

StudentManagerClient client = new StudentManagerClient ();
Client. GetOneStudentCompleted + = new EventHandler <GetOneStudentCompletedEventArgs> (client_GetOneStudentCompleted );
Client. GetOneStudentAsync ();
}

Void client_GetOneStudentCompleted (object sender, GetOneStudentCompletedEventArgs e)
{
If (e. Error = null)
{
LayoutRoot. DataContext = e. Result;
}
}

Private void Submit_Click (object sender, RoutedEventArgs e)
{
// Click a breakpoint to view the effect of the data binding mode.
Student tempStu = LayoutRoot. DataContext as Student;
}
}

Running result:

Change the age from 22 to 2222:

Memory Data Objects:

Change the binding Mode Value to TwoWay, XAML:

<Grid x: Name = "LayoutRoot" Background = "White">
<Grid. ColumnDefinitions>
<ColumnDefinition Width = "100" type = "codeph" text = "/codeph"/>
<ColumnDefinition/>
</Grid. ColumnDefinitions>
<Grid. RowDefinitions>
<RowDefinition Height = "Auto"/>
<RowDefinition Height = "Auto"/>
<RowDefinition Height = "Auto"/>
<RowDefinition Height = "Auto"/>
</Grid. RowDefinitions>

<TextBlock Text = "name:" HorizontalAlignment = "Right"> </TextBlock>
<TextBox x: Name = "NameTxt" Text = "{Binding Name, Mode = TwoWay, ValidatesOnExceptions = True, TargetNullValue = 'name cannot be blank ', fallbackValue = 'n'/A'} "Width =" 300 "HorizontalAlignment =" Left "Grid. column = "1"> </TextBox>
<TextBlock Text = "Age:" HorizontalAlignment = "Right" Grid. Row = "1"> </TextBlock>
<TextBox x: Name = "AgeTxt" Text = "{Binding Age, Mode = TwoWay, ValidatesOnExceptions = True, TargetNullValue = 'Age cannot be less than 1 ', fallbackValue = 'n'/A'} "Width =" 300 "Grid. row = "1" Grid. column = "1" HorizontalAlignment = "Left"> </TextBox>
<Button x: Name = "Submit" Content = "View data binding mode" Width = "150" Grid. row = "2" Grid. column = "1" HorizontalAlignment = "Left" Click = "Submit_Click"> </Button>
<Button x: Name = "ChangeValue" Content = "modify memory data object Value" Width = "150" Grid. row = "3" Grid. column = "1" HorizontalAlignment = "Left" Click = "ChangeValue_Click"> </Button>
</Grid>

The data verification attributes such as ValidatesOnExceptions, TargetNullValue, and FallbackValue are used in the above binding,

  • When ValidatesOnExceptions is set to True, if an exception is thrown, the validity is executed and a friendly error message is displayed to the user.
  • TargetNullValue. If the bound property value is Null, the value of TargetNullValue is used.
  • FallbackValue: if the data object does not have a bound attribute, the value of this attribute is displayed, prompting you

The memory data objects are as follows:

In many practical development scenarios, it is very likely to directly modify the attribute values of memory data objects, but the data context value of user interfaces has indeed changed, however, the data displayed on the interface is still raw data. To solve this problem, the data class must inherit the INotifyPropertyChanged interface. This interface defines a PropertyChanged event. If the value of a data object changes, the event must be triggered to notify the user interface to change the response value. Model diagram:

Inherit the data class after INotifyPropertyChanged:

[DataContract ()]
Public class Student: INotifyPropertyChanged
{
// Implement the INotifyPropertyChanged Interface
Public event PropertyChangedEventHandler PropertyChanged;
Public void OnPropertyChanged (PropertyChangedEventArgs e)
{
If (PropertyChanged! = Null)
{
PropertyChanged (this, e );
}
}

[DataMember ()]
Public string Name
{
Get;
Set;
}

[DataMember ()]
Public int Age
{
Get;
Set;
}
}

After the INotityPropertyChanged interface is inherited, the data displayed on the user interface changes with the memory data object. If you have any incorrect information or suggestions, please let me know.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.