Mega Code Archive
Implementing Data Binding in Silverlight Applications
//File:Page.xaml.cs
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
namespace SilverlightApplication3
{
public partial class MainPage : UserControl
{
Contact personA, personB, current;
Boolean isCurrentA;
public MainPage()
{
InitializeComponent();
initData();
setContext(personA);
isCurrentA = true;
UpdateBtn.Click += new RoutedEventHandler(doUpdate);
SwitchBtn.Click += new RoutedEventHandler(doSwitch);
}
void initData()
{
personA = new Contact();
personA.Name = "Mike";
personA.Numbers =
new List() { "111-222-333", "444-555-6666" };
personB = new Contact();
personB.Name = "Ted";
personB.Numbers =
new List() { "123-456-7890", "098-765-4321" };
}
void setContext(Contact c)
{
current = c;
LayoutRoot.DataContext = c;
}
void doUpdate(object sender, RoutedEventArgs e)
{
current.Name = nameBox.Text;
}
void doSwitch(object sender, RoutedEventArgs e)
{
if (isCurrentA)
{
setContext(personB);
isCurrentA = false;
}
else
{
setContext(personA);
isCurrentA = true;
}
}
}
public class Contact : INotifyPropertyChanged
{
private string ContactName;
private List ContactNumbers;
public event PropertyChangedEventHandler PropertyChanged;
public Contact()
{
}
public void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(property));
}
}
public string Name
{
get { return ContactName; }
set
{
ContactName = value;
NotifyPropertyChanged("Name");
}
}
public List Numbers
{
get { return ContactNumbers; }
set
{
ContactNumbers = value;
NotifyPropertyChanged("Numbers");
}
}
}
}