WPF学习笔记12. Binding (5)
2010-10-11 16:35:20 来源:本站整理(2) ObjectDataProvider
ObjectDataProvider 比我们直接绑定对象有如下三个好处:
可以在 XAML 申明中使用构造参数。
绑定到源对象的方法上。
支持异步数据绑定。
我们先看看构造参数的使用。
Window1.xaml.cs
enum Sex
{
Male,
Female
}
class Personal
{
public string Name { get; private set; }
public int Age { get; private set; }
public Sex Sex { get; private set; }
public Personal(string name, int age, Sex sex)
{
this.Name = name;
this.Age = age;
this.Sex = sex;
}
}
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
Window1.xaml
<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Learn.WPF"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="Window1">
<Window.Resources>
<ObjectDataProvider x:Key="personal" ObjectType="{x:Type my:Personal}">
<ObjectDataProvider.ConstructorParameters>
<sys:String>Tom</sys:String>
<sys:Int32>15</sys:Int32>
<my:Sex>Male</my:Sex>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<StackPanel DataContext="{StaticResource personal}">
<Label Content="{Binding Name}" />
<Label Content="{Binding Age}" />
<Label Content="{Binding Sex}" />
</StackPanel>
</Grid>
</Window>
更多精彩
赞助商链接