示例
MainWindow.xaml
<Window
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"
xmlns:local="clr-namespace:WpfTest"
xmlns:Properties="clr-namespace:WpfTest.Properties"
xmlns:wpf="http://schemas.microsoft.com/netfx/2007/xaml/presentation" x:Class="WpfTest.MainWindow"
mc:Ignorable="d"
Title="MainWindow" Height="250" Width="400">
<!--资源通常定义在根节点,或者资源字典中-->
<Window.Resources>
<DataTemplate x:Key="myTaskTemplate">
<Border Name="border" BorderBrush="Aqua" BorderThickness="1"
Padding="5" Margin="5" Width="250">
<StackPanel>
<TextBlock Text="{Binding Path=TaskName}"/>
<TextBlock Text="{Binding Path=Description}"/>
<TextBlock Text="{Binding Path=Priority}"/>
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox Name="listBox" Width="300" Margin="10"
ItemTemplate="{StaticResource myTaskTemplate}"/>
</Grid>
</Window>
MainWindow.xaml.cs
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.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;//INotifyPropertyChanged
using System.Threading.Tasks;
namespace WpfTest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public List<ItemData> myTodoList;
public MainWindow()
{
InitializeComponent();
List<ItemData> list = new List<ItemData>();
list.Add(new ItemData { TaskName = "A", Description = "aaa", Priority = 1 });
list.Add(new ItemData { TaskName = "B", Description = "bbb", Priority = 2 });
list.Add(new ItemData { TaskName = "C", Description = "ccc", Priority = 3 });
this.listBox.ItemsSource = list;
}
}
public class ItemData
{
// 注意:
// 字段无法直接数据绑定
// 只有属性才能与{Binding Path=*}绑定
public string TaskName { get; set; }
public string Description { get; set; }
public int Priority { get; set; }
}
}
运行测试