抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

在制作UWP个人项目时需要用到数据绑定,网上的教程大都不全,特此记录下自己使用的方法.

绑定源

指定一个类用来保存数据,以我自己的项目为例,需要定义“邮件”类.

MailSystem_UWP.Bean.Email

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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";
}
}
}

为绑定源定义集合

1
private static ObservableCollection<Email> data = new ObservableCollection<Email>();

当UWP进行了页面跳转,即使使用GoBack()来返回,原页面也会重新加载,因此建议使用静态类来避免数据丢失,并且修改集合时也不需要获取MainPage的实例

创建绑定

在xaml文件头定义命名空间

由于我的Email类在MailSystem_UWP.Bean下,因此定义该命名空间为local

1
xmlns:local="using:MailSystem_UWP.Bean"

在xaml文件的Page标签内定义模板

1
2
3
4
5
6
7
8
9
<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方法,像这样

1
public int id { get; set; }

对于非字符串变量,例如System.DateTime,系统会自动调用toString()

DataTemplate内即为数据模板,ListView会根据模板逐一添加控件

现在为ListView加上ItemTemplate属性

1
2
3
4
5
6
7
8
9
10
<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的构造函数里绑定数据源

1
2
3
4
5
public MainPage()
{
this.InitializeComponent();
listView.ItemsSource = data;
}

添加数据

直接为data添加数据,ListView中会自动更新

1
2
3
4
5
6
data.Clear();
for(int i = 0; i < emails.Count; i++)
{
//emails是ArrayList<Email>的实例
data.Add(emails[i]);
}

DearXuan

完整代码

MailSystem.Bean.Email

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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获取项目源文件

评论