在制作UWP个人项目时需要用到数据绑定,网上的教程大都不全,特此记录下自己使用的方法。
绑定源
指定一个类用来保存数据,以我自己的项目为例,需要定义“邮件”类。
MailSystem_UWP.Bean.Email
代码语言:javascript复制namespace MailSystem_UWP.Bean
{
/*
* mail_table:
* id:int
* sender:varchar(10)
* receiver:varchar(10)
* title:varchar(50)
* content:varchar(500)
* time:datetime
* state:int
*/
public class Email
{
public enum STATE
{
Delivery = 0,//送达
RecipientNotFound = 1,//找不到收件人
Deleted = 2//已被删除
}
public int id { get; set; }
public string sender { get; set; }
public string receiver { get; set; }
public string title { get; set; }
public string content { get; set; }
public DateTime time { get; set; }
public STATE state { get; set; }
public Email() { }
public Email(MySqlDataReader reader)
{
LoadFromReader(reader);
}
/// <summary>
/// 从MySqlDataReader获取User实例
/// </summary>
/// <param name="reader">MySqlDataReader实例</param>
public void LoadFromReader(MySqlDataReader reader)
{
id = reader[0].ToString().ToInt();
sender = reader[1].ToString();
receiver = reader[2].ToString();
title = reader[3].ToString();
content = reader[4].ToString();
time = reader.GetDateTime(5);
state = (STATE)reader[6].ToString().ToInt();
}
/// <summary>
/// 获取概要,用于显示在TextBlock中
/// </summary>
/// <returns>string类型:标题 "n" 概要</returns>
public string GetDescription()
{
return (content.Length <= Value.UserForm.DESCRIPTION_MAX_LENGTH
? content
: content.Substring(0, Value.UserForm.DESCRIPTION_MAX_LENGTH) "...")
"n";
}
}
}
为绑定源定义集合
代码语言:javascript复制private static ObservableCollection<Email> data = new ObservableCollection<Email>();
当UWP进行了页面跳转,即使使用GoBack()来返回,原页面也会重新加载,因此建议使用静态类来避免数据丢失,并且修改集合时也不需要获取MainPage的实例
创建绑定
在xaml文件头定义命名空间
由于我的Email类在MailSystem_UWP.Bean下,因此定义该命名空间为local
代码语言:javascript复制xmlns:local="using:MailSystem_UWP.Bean"
在xaml文件的Page标签内定义模板
代码语言:javascript复制<Page.Resources>
<DataTemplate x:Key="EMAIL" x:DataType="local:Email">
<Grid Height="80" Margin="0,0,0,0">
<TextBlock HorizontalAlignment="Left" Margin="10,10,0,0" Text="{x:Bind title}" TextWrapping="Wrap" VerticalAlignment="Top" FontWeight="Bold"/>
<TextBlock Margin="0,10,10,0" Text="{x:Bind time}" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Right" Width="auto" FontWeight="Normal"/>
<TextBlock HorizontalAlignment="Left" Margin="10,34,0,10" Text="{x:Bind content}" TextWrapping="Wrap" Width="408"/>
</Grid>
</DataTemplate>
</Page.Resources>
{x:Bind name}指向绑定源的name属性,你需要实现name的get和set方法,像这样
代码语言:javascript复制public int id { get; set; }
对于非字符串变量,例如System.DateTime,系统会自动调用toString()
DataTemplate内即为数据模板,ListView会根据模板逐一添加控件
现在为ListView加上ItemTemplate属性
代码语言:javascript复制<ListView
x:Name="listView"
ItemTemplate="{StaticResource EMAIL}"
HorizontalAlignment="Left"
Width="325"
Margin="0,55,0,0"
Background="White"
SelectionChanged="onSelectionChange"
IsItemClickEnabled="True"
ItemClick="onItemClick"/>
在MainPage的构造函数里绑定数据源
代码语言:javascript复制public MainPage()
{
this.InitializeComponent();
listView.ItemsSource = data;
}
添加数据
直接为data添加数据,ListView中会自动更新
代码语言:javascript复制data.Clear();
for(int i = 0; i < emails.Count; i )
{
//emails是ArrayList<Email>的实例
data.Add(emails[i]);
}
完整代码
MailSystem.Bean.Email
代码语言:javascript复制using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using MailSystem_UWP.Support;
namespace MailSystem_UWP.Bean
{
/*
* mail_table:
* id:int
* sender:varchar(10)
* receiver:varchar(10)
* title:varchar(50)
* content:varchar(500)
* time:datetime
* state:int
*/
public class Email
{
public enum STATE
{
Delivery = 0,//送达
RecipientNotFound = 1,//找不到收件人
Deleted = 2//已被删除
}
public int id { get; set; }
public string sender { get; set; }
public string receiver { get; set; }
public string title { get; set; }
public string content { get; set; }
public DateTime time { get; set; }
public STATE state { get; set; }
public Email() { }
public Email(MySqlDataReader reader)
{
LoadFromReader(reader);
}
/// <summary>
/// 从MySqlDataReader获取User实例
/// </summary>
/// <param name="reader">MySqlDataReader实例</param>
public void LoadFromReader(MySqlDataReader reader)
{
id = reader[0].ToString().ToInt();
sender = reader[1].ToString();
receiver = reader[2].ToString();
title = reader[3].ToString();
content = reader[4].ToString();
time = reader.GetDateTime(5);
state = (STATE)reader[6].ToString().ToInt();
}
/// <summary>
/// 获取概要,用于显示在TextBlock中
/// </summary>
/// <returns>string类型:标题 "n" 概要</returns>
public string GetDescription()
{
return (content.Length <= Value.UserForm.DESCRIPTION_MAX_LENGTH
? content
: content.Substring(0, Value.UserForm.DESCRIPTION_MAX_LENGTH) "...")
"n";
}
}
}
MainPage.xaml
代码语言:javascript复制<Page x:Name="mainPage"
x:Class="MailSystem_UWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MailSystem_UWP.Bean"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="744" d:DesignHeight="532">
<Page.Resources>
<DataTemplate x:Key="EMAIL" x:DataType="local:Email">
<Grid Height="80" Margin="0,0,0,0">
<TextBlock HorizontalAlignment="Left" Margin="10,10,0,0" Text="{x:Bind title}" TextWrapping="Wrap" VerticalAlignment="Top" FontWeight="Bold"/>
<TextBlock Margin="0,10,10,0" Text="{x:Bind time}" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Right" Width="auto" FontWeight="Normal"/>
<TextBlock HorizontalAlignment="Left" Margin="10,34,0,10" Text="{x:Bind content}" TextWrapping="Wrap" Width="408"/>
</Grid>
</DataTemplate>
</Page.Resources>
<Grid>
<ListView x:Name="listView" ItemTemplate="{StaticResource EMAIL}" HorizontalAlignment="Left" Width="325" Margin="0,55,0,0" Background="White" SelectionChanged="onSelectionChange" IsItemClickEnabled="True" ItemClick="onItemClick"/>
<!--这里是其它控件-->
</Grid>
</Page>
MainPage.xaml.cs
代码语言:javascript复制using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using MailSystem_UWP.View;
using MailSystem_UWP.Bean;
using Windows.UI.Xaml.Media.Imaging;
using System.Windows.Input;
using System.Collections.ObjectModel;
// https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x804 上介绍了“空白页”项模板
namespace MailSystem_UWP
{
public sealed partial class MainPage : Page
{
//已经删除了不相关的代码
//数据绑定
private static ObservableCollection<Email> data = new ObservableCollection<Email>();
public MainPage()
{
this.InitializeComponent();
listView.ItemsSource = data;
}
public void LoadEmail(List<Email> emails)
{
data.Clear();
for(int i = 0; i < emails.Count; i )
{
data.Add(emails[i]);
}
}
}
}
源文件
前往Gitee获取项目源文件
MailSystem_UWP
https://gitee.com/dearxuan/mail-system_-uwp