How binding of Silverlight UI to .NET Classes works
I am looking at binding a certain silverlight UI to a C# class. In the example code below there are two textboxes in the XAML page. Any changes made to one textbox is reflected in the other the minute it loses focus and vice-versa. While the example I have works as I want it to, I have no clue as to what is goin on under the hood and how it works that way.
Here is the C# code
public class Person : INotifyPropertyChanged
{
public string FirstName
{
get
{return firstname;}
set
{ firstname = value;
FirePropertyChanged("FirstName");
}
}
private string firstname;
void FirePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Grid in the mainpage.xaml
<Grid x:Name="MyLayoutRoot" Background="White" ShowGridLines="True">
<TextBox Text="{Binding FirstName, Mode=TwoWay}" Grid.Column="1"></TextBox>
<TextBox Text="{Binding FirstName, Mode=TwoWay}" Grid.Column="1" Grid.Row="3"></TextBox>
</Grid>
Codebehind for Mainpage.xaml
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
Person p = new Person()
{
FirstName ="Dee"
};
MyLayoutRoot.DataContext = p;
}
}
My understanding so far which is a bit hazy now is this:
The textbox in the xaml(mainpage.xaml) knows what property to bind to based on its "Binding" tag, from the class (Person) it was setup with, in the xaml codebehind file(mainpage.xaml.cs) by using the datacontext property there.
INotifyPropertyChanged is an interface in the person class, that provides some hook that allows the Xaml UI to know when the Firstname property got changed in the UI. The minute the Firstname property is set, the FirePropertyChanged method gets called which triggers this event PropertyChangedEventHandler as is implemented in this line
PropertyChanged(this, new PropertyChangedEventArgs(property));
Can anyone elaborate on what goes on behind the scenes here at this moment, when one of开发者_JS百科 the textboxes changes and loses focus; and how does the Binding property on the Silverlight client side UI, maintain contact with the C# class which, correct me if I am wrong is still on the server that the silverlight UI was downloaded from.
Thanks for your time.
If the Person class is in the same Silverlight UI project, then it is actually on the client (not the server). Maybe this makes it easier to understand?
精彩评论