這個例子中被繫結資料是一個owner類的執行個體,現在silverlight項目中添加一個owner類
Class Owner
public class Owner
{
public int OwnerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public DateTime BirthDate { get; set; }
public DateTime CustomerSince { get; set; }
public string ImageName { get; set; }
public DateTime LastActivityDate { get; set; }
public double CurrentBalance { get; set; }
public double LastActivityAmount { get; set; }
}
然後在MainPage.xaml.cs中建立一個Owner類的執行個體
MainPage.xaml.cs
public MainPage()
{
InitializeComponent();
InitializeOwner();
}
private void InitializeOwner()
{
owner = new Owner();
owner.OwnerId = 1234567;
owner.FirstName = "Zhu";
owner.LastName = "jz";
owner.Address = "ChaoYang BJ";
owner.ZipCode = "100001";
owner.City = "BeiJing";
owner.Country = "China";
owner.State = "BeiJing";
owner.ImageName = "wo.jpg";
owner.LastActivityAmount = 100;
owner.LastActivityDate = DateTime.Today;
owner.CurrentBalance = 1234.56;
owner.BirthDate = new DateTime(1986, 6, 8);
owner.CustomerSince = new DateTime(2009, 12, 20);
}
到此,已經通過使用擴充標識文法(Markup Extension)實現了綁定到TextBlock的Text屬性。就差最後一步,將Owner類執行個體綁定到控制項,由下面代碼來實現:
public MainPage()
{
InitializeComponent();
InitializeOwner();
OwnerDetailsGrid.DataContext = owner;
}
效果如下:
回過頭來再看XAML代碼,上面說過,這兒是通過擴充標識實現TextBlock的資料繫結:
<TextBlock Text="{Binding CustomerSince}" />
實際上這是一種縮寫寫法,完整的綁定文法如下:
<TargetControl TargetProperty="{Binding SourceProperty,SomeBindingProperties}" />