A Simple Silverlight Data Binding
2011-08-22
Data binding in Silverlight is accomplished by using Binding class. There are 2 components in Binding class: the source and the target, and binding mode which indicates the binding way is one way or two way.
MainPage.xaml:
<UserControl x:Class="SLDataBind.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Loaded="UserControl_Loaded" d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="Full Name" VerticalAlignment="Center" Margin="5" Grid.Row="0" />
<TextBlock Text="Phone Number" VerticalAlignment="Center" Margin="5" Grid.Row="1" />
<TextBox Text="{Binding FullName}" Height="24" Margin="5" Grid.Column="1" Grid.Row="0" />
<TextBox Text="{Binding PhoneNo}" Height="24" Margin="5" Grid.Column="1" Grid.Row="1" />
</Grid>
</UserControl>
MainPage.xaml.cs:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
Person p = new Person { FullName = "Jason", PhoneNo = "416-123-4567" };
this.LayoutRoot.DataContext = p;
}
}
public class Person
{
public string FullName
{
get;
set;
}
public string PhoneNo
{
get;
set;
}
}
There is a good article from MSDN about Silverlight data binding, please read it.