WPF_AutoCompleteBox智能提示_Xml读写
效果图
1.需要引用的DLL
2. Window.xaml
<Window x:Class="自己的命名空间"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tookit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
xmlns:viewModel="clr-namespace:ViewModel;assembly=ViewModel"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Button Name="SaveXml" Content="从数据库获取最新数据" Grid.Row="2" Margin="23,0,364,0" Click="SaveXml_OnClick"></Button>
<tookit:AutoCompleteBox x:Name="searchTextBox" Grid.Row="1"
ValueMemberPath="SerchString" Margin="10,11,209,28"
FontSize="20" Foreground="Black"
IsTextCompletionEnabled="True">
<tookit:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="5,5" FontSize="20">
<Run Text="{Binding SerchString}" Foreground="Blue"/>
<Run Text="{Binding Name}" Foreground="Gray"/>
</TextBlock>
</DataTemplate>
</tookit:AutoCompleteBox.ItemTemplate>
</tookit:AutoCompleteBox>
<TextBlock Margin="23,36,35,-196" Grid.Row="2" Name="MyShow"/>
</Grid>
</Window>
3.Window.xaml.cs
using DAL;
using Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Utility;
namespace 自己的命名空间
{
public partial class ShellWindow : Window
{
/// <summary>
/// 数据源
/// </summary>
public List<AutoCompleteModel> AutoCompleteList = new List<AutoCompleteModel>();
/// <summary>
/// 构造函数
/// </summary>
public ShellWindow()
{
InitializeComponent();
searchTextBox.SelectionChanged += SearchTextBox_SelectionChanged;
searchTextBox.Populating += SearchTextBox_Populating;
ReadXml();
this.searchTextBox.ItemsSource = AutoCompleteList;
this.searchTextBox.FilterMode = AutoCompleteFilterMode.Contains;
}
/// <summary>
/// 读xml文件
/// </summary>
public void ReadXml()
{
string path = "Files/XmlFile/CustomerAutoCompleteXml.xml";
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/" + path))
{
using (FileStream fsRead = new FileStream(path, FileMode.Open))
{
int fsLen = (int)fsRead.Length;
byte[] heByte = new byte[fsLen];
int r = fsRead.Read(heByte, 0, heByte.Length);
string xmlStr = System.Text.Encoding.UTF8.GetString(heByte);
AutoCompleteList = XmlHelper.Deserialize(typeof(List<AutoCompleteModel>), xmlStr) as List<AutoCompleteModel>;
}
}
else
{
MessageBox.Show(path + "文件不存在");
}
}
private void SearchTextBox_Populating(object sender, PopulatingEventArgs e)
{
e.Cancel = true;
//获取输入的值
var inputText = searchTextBox.Text;
Task.Run(() =>
{
string text = inputText;
//判断输入是否是中文(根据自己的需求)
for (int i = 0; i < text.Length; i++)
{
if ((int)text[i] > 127)
continue;
else
return;
}
//使用Ui线程的Dispatcher 操作控件
this.Dispatcher.BeginInvoke(new Action(() =>
{
//开始匹配
this.searchTextBox.PopulateComplete();
}), DispatcherPriority.SystemIdle, null);
});
}
/// <summary>
/// 选择改变事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SearchTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
AutoCompleteModel model = this.searchTextBox.SelectedItem as AutoCompleteModel;
if (model != null)
{
//拿到 选择的值(显示到页面上)
MyShow.Text = model.SerchString;
}
}
/// <summary>
/// 获取最新数据的 按钮 事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveXml_OnClick(object sender, RoutedEventArgs e)
{
SaveDataXml();
}
/// <summary>
/// 获取最新的数据
/// </summary>
public async void SaveDataXml()
{
await Task.Run(() =>
{
CustomerDal dal = new CustomerDal();
//数据库查询出所有数据
var res = dal.AutoCompleteCustomerModelByCustomerName("");
//存放AutoCompleteModel的集合
List<AutoCompleteModel> xmlList = new List<AutoCompleteModel>();
//将数据库数据.转为 List<AutoCompleteModel>
res.ForEach((item) =>
{
AutoCompleteModel model = new AutoCompleteModel();
model.SerchString = item.CustomerName;
model.Name = item.CustomerId.ToString();
xmlList.Add(model);
});
// 将list序列化
string xmlStr = XmlHelper.Serializer(typeof(List<AutoCompleteModel>), xmlList);
//转换为字节
byte[] myByte = System.Text.Encoding.UTF8.GetBytes(xmlStr);
//判断相应月份文件夹是否存在,没有则创建
string path = "Files/XmlFile/";
if (System.IO.Directory.Exists(path))
{
MessageBox.Show("存在相应文件夹");
}
else
{
System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(path);
directoryInfo.Create();
MessageBox.Show("不存在相应文件夹,已自动创建");
}
//设置路径和 写入方式 (create 是 如果存在则覆盖 )
using (FileStream fsWrite = new FileStream(path + "CustomerAutoCompleteXml.xml", FileMode.Create))
{
fsWrite.Write(myByte, 0, myByte.Length);
};
//读取数据
ReadXml();
});
//指定Sourse
this.searchTextBox.ItemsSource = AutoCompleteList;
}
}
}
4.XmlHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
namespace Utility
{
/// <summary>
/// Xml序列化与反序列化
/// </summary>
public class XmlHelper
{
#region 反序列化
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="xml">XML字符串</param>
/// <returns></returns>
public static object Deserialize(Type type, string xml)
{
try
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmldes = new XmlSerializer(type);
var res= xmldes.Deserialize(sr);
return res;
}
}
catch (Exception e)
{
return null;
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="xml"></param>
/// <returns></returns>
public static object Deserialize(Type type, Stream stream)
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(stream);
}
#endregion
#region 序列化
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="obj">对象</param>
/// <returns></returns>
public static string Serializer(Type type, object obj)
{
MemoryStream Stream = new MemoryStream();
XmlSerializer xml = new XmlSerializer(type);
try
{
//序列化对象
xml.Serialize(Stream, obj);
}
catch (InvalidOperationException)
{
throw;
}
Stream.Position = 0;
StreamReader sr = new StreamReader(Stream);
string str = sr.ReadToEnd();
sr.Dispose();
Stream.Dispose();
return str;
}
#endregion
}
}
#region xml序列化和反序列化
//1. 实体对象转换到Xml
//public class Student
//{
// public string Name { set; get; }
// public int Age { set; get; }
//}
//Student stu1 = new Student() { Name = "okbase", Age = 10 };
//string xml = XmlUtil.Serializer(typeof(Student), stu1);
//Console.Write(xml);
//2. Xml转换到实体对象
//Student stu2 = XmlUtil.Deserialize(typeof(Student), xml) as Student;
//Console.Write(string.Format("名字:{0},年龄:{1}", stu2.Name, stu2.Age));
//3. DataTable转换到Xml
//// 生成DataTable对象用于测试
//DataTable dt1 = new DataTable("mytable"); // 必须指明DataTable名称
//dt1.Columns.Add("Dosage", typeof(int));
//dt1.Columns.Add("Drug", typeof(string));
//dt1.Columns.Add("Patient", typeof(string));
//dt1.Columns.Add("Date", typeof(DateTime));
//// 添加行
//dt1.Rows.Add(25, "Indocin", "David", DateTime.Now);
//dt1.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
//dt1.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
//dt1.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
//dt1.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
//// 序列化
//xml = XmlUtil.Serializer(typeof(DataTable), dt1);
//Console.Write(xml);
//4. Xml转换到DataTable
//// 反序列化
//DataTable dt2 = XmlUtil.Deserialize(typeof(DataTable), xml) as DataTable;
//// 输出测试结果
//foreach (DataRow dr in dt2.Rows)
//{
// foreach (DataColumn col in dt2.Columns)
// {
// Console.Write(dr[col].ToString() + " ");
// }
// Console.Write("\r\n");
//}
//5. List转换到Xml
//// 生成List对象用于测试
//List<Student> list1 = new List<Student>(3);
//list1.Add(new Student() { Name = "okbase", Age = 10 });
//list1.Add(new Student() { Name = "csdn", Age = 15 });
//// 序列化
//xml = XmlUtil.Serializer(typeof(List<Student>), list1);
//Console.Write(xml);
//6. Xml转换到List
//List<Student> list2 = XmlUtil.Deserialize(typeof(List<Student>), xml) as List<Student>;
//foreach (Student stu in list2)
//{
// Console.WriteLine(stu.Name + "," + stu.Age.ToString());
//}
#endregion
#region 文件流的读写
////C#文件流写文件,默认追加FileMode.Append
//string msg = "okffffffffffffffff";
//byte[] myByte = System.Text.Encoding.UTF8.GetBytes(msg); //转换为字节
//using (FileStream fsWrite = new FileStream(@"D:\1.txt", FileMode.Append))
//{
// fsWrite.Write(myByte, 0, myByte.Length);
//};
////c#文件流读文件
//using (FileStream fsRead = new FileStream(@"D:\1.txt", FileMode.Open))
//{
// int fsLen = (int)fsRead.Length;
// byte[] heByte = new byte[fsLen];
// int r = fsRead.Read(heByte, 0, heByte.Length);
// string myStr = System.Text.Encoding.UTF8.GetString(heByte);
// Console.WriteLine(myStr);
// Console.ReadKey();
//}
#endregion
WPF_AutoCompleteBox智能提示_Xml读写的更多相关文章
- Eclipse代码和xml文件的智能提示
一.代码智能提示 Windows → Preferences → Java→ Editor → Content Assist 将 Auto activation delay(ms): 改为 0 将 A ...
- Laravel 安装代码智能提示扩展「laravel-ide-helper」
========================laravel-ide-helper======================== 使用 Laravel 框架IDE居然没有智能提示?这感觉实在太糟糕 ...
- 利用typescript使backbone强类型智能提示
模型类一旦多了没有强类型和智能提示是相当痛苦的,所以. 仅仅用ts定义一个模型类: class Person extends Backbone.Model { defaults = { Name:&q ...
- Visual Studio Code 智能提示文件
Visual Studio Code 开发前端和node智能提示 visual studio code 是一个很好的编辑器,可以用来编写前端代码和nodejs. 我很喜欢使用VSC,现在流行框架对VS ...
- jQuery打造智能提示插件二(可编辑下拉框)
在上一篇 jQuery打造智能提示插件 上改进,增加下拉按钮,修复点击下拉区域外不隐藏BUG 效果 下拉按钮素材: js封装,注意红色部分为BUG修复,然后传入boxwidth不带px: /* /// ...
- 五小步让VS Code支持AngularJS智能提示
本文想通过配置VS Code来实现对AngularJS的智能提示.在一般的情况下对于在HTML页面是支持提示的.但是在js页面就不是很友好,它是记忆你之前的输入,要是之后有重复的输入,VS Code会 ...
- Xamarin.Android之布局文件智能提示问题
一.前言 看到有人问关于xamarin.android的布局没智能提示问题(VS 2015),当然,写布局这东西没提示这是一件相对痛苦的事 ,所以这里就提供一个解决的方案! 二.解决方案 想要智能提示 ...
- 让Visual Studio Code对jQuery支持智能提示!
本人新手,对代码各种不熟悉,记不准确,总是打错,造成各种失误!! 其实这个方法应该适合大部分前端开发工具!! 园里子有前人写了一篇文章对智能提示的实现!不过很多新手看不懂吧. http://www.c ...
- 使用jsonp跨域调用百度js实现搜索框智能提示,并实现鼠标和键盘对弹出框里候选词的操作【附源码】
项目中常常用到搜索,特别是导航类的网站.自己做关键字搜索不太现实,直接调用百度的是最好的选择.使用jquery.ajax的jsonp方法可以异域调用到百度的js并拿到返回值,当然$.getScript ...
随机推荐
- WebUploader 上传图片回显
/* fileMaxCount 最大文件数 buttonText 按钮文本 multiple 是否多选 */ (function ($) { $.fn.extend({ uploadImg: func ...
- 如何导出robotframework的工程
不知道是不是只有我一个小白,自己折腾了很久,也百度了很久,不知道怎么导出哇.现在来扫扫盲罗.我拿自己的项目举例:找到我的RF工程目录可以看到下面有3个项目,直接拷贝你想要的项目就ok啦,是不是so e ...
- iOS - 基础知识总结(OC版) 面试必看 再不看就要用swift了
OC的理解与特性 OC作为一门面向对象的语言,自然具有面向对象的语言特性:封装.继承.多态.它既具有静态语言的特性(如C++),又有动态语言的效率(动态绑定.动态加载等).总体来讲,OC确实是一门不错 ...
- nginx 反向代理配置(一)
文章参考:https://blog.csdn.net/physicsdandan/article/details/45667357 什么是代理? 代理在普通生活中的意义就是本来 ...
- Chrome安装crx文件的插件时出现“程序包无效”
有趣的事,Python永远不会缺席! 如需转发,请注明出处:小婷儿的python https://www.cnblogs.com/xxtalhr/p/11043453.html 链接:https: ...
- Intellij里检出svn报错找不到svn解决办法
Intellij里检出svn报错找不到,解决办法: 1. 安装svn客户端: 2. 去掉settings->version control->subversion里的use command ...
- Mac下多版本JDK安装及管理
在Java项目中,经常对JDK版本有不同的要求,可是不可能为了某个项目的运行重新下载不同版本JDK进行安装,这样就涉及到对本地环境中多个JDK版本的管理. Mac的JDK都是安装到一个指定目录的:/L ...
- centos7 安装jdk及mysql8
安装jdk 1.上传压缩包:通过SSH上传jdk压缩包,比如上传至/usr/local/java目录下 2.解压压缩包:利用命令解压压缩包 tar -zxvf jdk-11.0.5_linux-x6 ...
- AM--消息队列
kafka rocketMq零拷贝对比 https://cloud.tencent.com/developer/news/333695 还有Linux目录下的基本原理 RocketMQ Kafka C ...
- python之csv操作
在使用python爬虫时或者其他情况,都会用到csv存储与读取的相关操作,我们在这里就浅谈一下: CSV(Comma-Separated Values)逗号分隔符,也就是每条记录中的值与值之间是用分号 ...