下面这个例子展示了WP开发中XAML与CS的数据绑定。XAML的数据绑定分为好几种,下面只是其中的一种。
<phone:PhoneApplicationPage
x:Class="BindingExample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:src="clr-namespace:BindingExample"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<Grid HorizontalAlignment="Left" Height="768" VerticalAlignment="Top" Width="480">
<Grid.Resources>
<src:Person x:Key="myExample" PersonName="Joe"/>
</Grid.Resources>
<TextBlock x:Name="Tb" HorizontalAlignment="Left" Margin="161,302,0,0" TextWrapping="Wrap" Text="{Binding Source={StaticResource myExample}, Path=PersonName}" VerticalAlignment="Top" Height="69" Width="173"/>
</Grid>
</phone:PhoneApplicationPage>
这里是主界面,里面有一个TextBlock,事例展示了TextBlock的Text属性的数据绑定。
首先简要介绍一下,在BindingExample的空间下有一个类Person,Text属性要和Person里面的PersonName属性进行绑定,所以首先声明了Resources,把Person类按照名称myExample声明为自己的资源,并且为PersonName属性赋值为Joe。
然后在TextBlock里面:
Text="{Binding Source={StaticResource myExample}, Path=PersonName}"
用Binding绑定了刚刚声明的静态资源myExample,然后用Path指定了要绑定的属性PersonName,因为刚刚已经为PersonName赋值为Joe了,所以这行实际上是为Text赋值为Joe。
最后附上Person类的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BindingExample
{
public class Person
{
public String PersonName { get; set; }
}
}