其中目标属性必须是依赖属性(DependencyProperty)
为了介绍说明方便首先定义个数据类:
public Person
{
public Age { get; ; }
public Name { get; ; }
}
例子1:
<ListBox x:Name="list1">
</ListBox>
public partial Page : UserControl
{
public Page
{
InitializeComponent;
var persons = List<Person>;
for(var i=0; i< 5; i)
{
persons.Add( Person {Name = "Person " + i., Age = 20 + i});
}
list1.DataContext = persons;
}
}
这里仅指定了 list1 DataContext 属性运行后发现页面没有显示
如果在页面里改改:
<ListBox x:Name="list1" ItemsSource="{Binding}">
</ListBox>
会发现绑定成功但是数据项显示为默认 Person 对象 后表示不太友好如下图:或者也可以将后台代码改成:
list1.ItemsSource = persons;
而页面 markup 仍然是: <ListBox x:Name="list1">
</ListBox>
这样也能绑定成功这里原因在于:ListBox 通过 ItemsSource 里数据去填充数据项所以直接给这个属性赋值是可以
或者通过空绑定语法 {Binding}指定 ItemsSource 属性绑定为数据源对象本身(未指定绑定路径)而数据源就是通过 DataContext 获得并且这个属性数据可以从父对象继承下来
下面给 ListBox 指定列表项数据模板让它显示好看点:
<ListBox x:Name="list1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Age}" Margin="20,0" />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
显示如下:还可以将 DataTemplate 定义到 App Resource 里去以便于重用
App.xaml:
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SilverlightTestApp.App"
>
<Application.Resources>
<DataTemplate x:Key="ListBoxDataTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Age}" Margin="20,0" />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</Application.Resources>
</Application>
Page.xaml:<UserControl x:Class="SilverlightTestApp.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<ListBox x:Name="list1" ItemTemplate="{StaticResource ListBoxDataTemplate}">
</ListBox>
</Grid>
</UserControl>
运行后效果样
最新评论