WPF主要做UI,所以数据邦定当然少不了。本节以ListBox为例,介绍数据邦定(和WinForm还是很有区别的哦)。
先建立一个WPFApplication Project. 在Window xaml里添加一个ListBox控件。
代码
<Window x:Class="WpfProject.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test" Height="300" Width="300" Loaded="Window_Loaded">
<Grid>
<ListBox Name="lbxPersons"></ListBox>
</Grid>
</Window>
引用一个Loaded事件来完成我们的邦定。大家知道,ListBox是一个ItemControl,所以我们通过设置ItemSource来邦定数据。
代码
public partial class Test : Window
{
public Test()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
List<Person> persons = new List<Person>{
new Person{FirstName="jimson",LastName="Ma"},
new Person{FirstName="Lingxia",LastName="Wang"}
};
this.lbxPersons.ItemsSource = persons;
}
}
public class Person{
public string LastName { set; get; }
public string FirstName { set; get; }
}
运行F5,结果:
显然这样是不成的。改进xaml:
代码
<Window x:Class="WpfProject.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test" Height="300" Width="300" Loaded="Window_Loaded">
<Grid>
<ListBox Name="lbxPersons">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName}" Width="50" />
<TextBlock Text="{Binding LastName}" Width="50" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
运行F5,结果:
这下正确了。但是有个问题,空值怎么办?看看这个:
代码
<Window x:Class="WpfProject.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test" Height="300" Width="300" Loaded="Window_Loaded">
<Grid>
<ListBox Name="lbxPersons">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName}" Width="50" />
<TextBlock Text="{Binding LastName}" Width="50" />
<TextBlock Text="{Binding Age, TargetNullValue='Age Unknown'}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfProject
{
/// <summary>
/// Interaction logic for Test.xaml
/// </summary>
public partial class Test : Window
{
public Test()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
List<Person> persons = new List<Person>{
new Person{FirstName="jimson",LastName="Ma", Age=23},
new Person{FirstName="Lingxia",LastName="Wang"}
};
this.lbxPersons.ItemsSource = persons;
}
}
public class Person{
public string LastName { set; get; }
public string FirstName { set; get; }
public int? Age { set; get; }
}
}
运行结果:
应用TargetNullValue,很好的处理了控制信息。