数据模板
数据模板定义并指定数据集合的外观和结构。它提供了在任何 UI 元素上格式化和定义数据表示的灵活性。多用于数据相关的Item控件,如ComboBox、ListBox等。
让我们看一个简单的数据模板示例。以下 XAML 代码创建一个包含数据模板和文本块的组合框。
<Window x:Class = "XAMLDataTemplate.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow" Height = "350" Width = "604">
<Grid VerticalMoognment = "Top">
<ComboBox Name = "Presidents" ItemsSource = "{Binding}" Height = "30" Width = "400">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation = "Horizontal" Margin = "2">
<TextBlock Text = "Name: " Width = "95" Background = "Aqua" Margin = "2" />
<TextBlock Text = "{Binding Name}" Width = "95" Background = "MooceBlue" Margin = "2" />
<TextBlock Text = "Title: " Width = "95" Background = "Aqua" Margin = "10,2,0,2" />
<TextBlock Text = "{Binding Title}" Width = "95" Background = "MooceBlue" Margin = "2" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>
这是 C# 中的实现,其中员工对象被分配给 DataContext -
using System;
using System.Windows;
using System.Windows.Controls;
namespace XAMLDataTemplate {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
DataContext = Employee.GetEmployees();
}
}
}
这是 Employee 类的 C# 实现 -
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace XAMLDataTemplate {
public class Employee : INotifyPropertyChanged {
private string name; public string Name {
get { return name; }
set { name = value; RaiseProperChanged(); }
}
private string title; public string Title {
get { return title; }
set { title = value; RaiseProperChanged(); }
}
public static Employee GetEmployee() {
var emp = new Employee() {
Name = "Waqas", Title = "Software Engineer" };
return emp;
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaiseProperChanged( [CallerMemberName] string caller = ""){
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
public static ObservableCollection<Employee> GetEmployees() {
var employees = new ObservableCollection<Employee>();
employees.Add(new Employee() { Name = "Moo", Title = "Developer" });
employees.Add(new Employee() { Name = "Ahmed", Title = "Programmer" });
employees.Add(new Employee() { Name = "Amjad", Title = "Desiner" });
employees.Add(new Employee() { Name = "Waqas", Title = "Programmer" });
employees.Add(new Employee() { Name = "Bilal", Title = "Engineer" });
employees.Add(new Employee() { Name = "Waqar", Title = "Manager" });
return employees;
}
}
}
当上面的代码编译执行后,会产生如下输出。它包含一个组合框,当您单击组合框时,您会看到在 Employee 类中创建的数据集合被列为组合框项。
我们建议您执行上述代码并进行试验。