7.创建动态绑定

适用于silverlight3、4、5

1. 新建一个项目,在MainPage.Xaml文件中添加控件,代码如下:

View Code
<UserControl x:Class="SilverlightApplication_DynamicBindings.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"

d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Background="White">

<Grid x:Name="GridMyself" >

<TextBlock x:Name="MyName"></TextBlock>

<TextBlock x:Name="MyAge" Margin="0,27,0,-27"></TextBlock>

<TextBlock x:Name="MySex" Margin="0,55,0,-55" ></TextBlock>

</Grid>

</Grid>

</UserControl>

2. 新建一个类Myself.cs作为数据源

View Code
using System;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace SilverlightApplication_DynamicBindings

{

public class MySelf

{

public string MyName { get; set; }

public int MyAge { get; set; }

public string MySex { get; set; }

}

}

3. 在MainPage.Xaml.cs 文件中,实例化类,并进行数据绑定

View Code
using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace SilverlightApplication_DynamicBindings

{

public partial class MainPage : UserControl

{

public MainPage()

{

InitializeComponent();

//初始化Myself实例

MySelf i = new MySelf();

MyName = "小刀";

MyAge = 24;

MySex = "";

//在C#代码中创建绑定

this.MyName.SetBinding(TextBlock.TextProperty, new System.Windows.Data.Binding("MyName"));

this.MyAge.SetBinding(TextBlock.TextProperty, new System.Windows.Data.Binding("MyAge"));

this.MySex.SetBinding(TextBlock.TextProperty, new System.Windows.Data.Binding("MySex"));

//将Grid的上下文设置问Myself实例

GridMyself.DataContext = i;

}

}

}

运行效果如下:

clip_image001

总结:在这个例子中,textblock控件的Text属性是在C#代码中绑定的,实在程序运行过程中动态绑定的。

原文地址:https://www.cnblogs.com/yuanjiedao/p/2934744.html