效果图

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读写的更多相关文章

  1. Eclipse代码和xml文件的智能提示

    一.代码智能提示 Windows → Preferences → Java→ Editor → Content Assist 将 Auto activation delay(ms): 改为 0 将 A ...

  2. Laravel 安装代码智能提示扩展「laravel-ide-helper」

    ========================laravel-ide-helper======================== 使用 Laravel 框架IDE居然没有智能提示?这感觉实在太糟糕 ...

  3. 利用typescript使backbone强类型智能提示

    模型类一旦多了没有强类型和智能提示是相当痛苦的,所以. 仅仅用ts定义一个模型类: class Person extends Backbone.Model { defaults = { Name:&q ...

  4. Visual Studio Code 智能提示文件

    Visual Studio Code 开发前端和node智能提示 visual studio code 是一个很好的编辑器,可以用来编写前端代码和nodejs. 我很喜欢使用VSC,现在流行框架对VS ...

  5. jQuery打造智能提示插件二(可编辑下拉框)

    在上一篇 jQuery打造智能提示插件 上改进,增加下拉按钮,修复点击下拉区域外不隐藏BUG 效果 下拉按钮素材: js封装,注意红色部分为BUG修复,然后传入boxwidth不带px: /* /// ...

  6. 五小步让VS Code支持AngularJS智能提示

    本文想通过配置VS Code来实现对AngularJS的智能提示.在一般的情况下对于在HTML页面是支持提示的.但是在js页面就不是很友好,它是记忆你之前的输入,要是之后有重复的输入,VS Code会 ...

  7. Xamarin.Android之布局文件智能提示问题

    一.前言 看到有人问关于xamarin.android的布局没智能提示问题(VS 2015),当然,写布局这东西没提示这是一件相对痛苦的事 ,所以这里就提供一个解决的方案! 二.解决方案 想要智能提示 ...

  8. 让Visual Studio Code对jQuery支持智能提示!

    本人新手,对代码各种不熟悉,记不准确,总是打错,造成各种失误!! 其实这个方法应该适合大部分前端开发工具!! 园里子有前人写了一篇文章对智能提示的实现!不过很多新手看不懂吧. http://www.c ...

  9. 使用jsonp跨域调用百度js实现搜索框智能提示,并实现鼠标和键盘对弹出框里候选词的操作【附源码】

    项目中常常用到搜索,特别是导航类的网站.自己做关键字搜索不太现实,直接调用百度的是最好的选择.使用jquery.ajax的jsonp方法可以异域调用到百度的js并拿到返回值,当然$.getScript ...

随机推荐

  1. Informix从一个表更新多选数据到另一个表

    功能如题, Informix从一个表更新多选数据到另一个表 例如, 要更新tab01的几个字段数据, 这些数据来自tab02, tab01和tab02之间通过id关联 参考语句: update tab ...

  2. mybatis获取刚刚插入到数据库的数据的id(转载)

    原文地址:https://blog.csdn.net/hehuihh/article/details/82800739 我用的是第一种写法,直接把代码copy到insert标签里(id要是自增id) ...

  3. MySQL中You can't specify target table '表名'('sn_app_label') for update in FROM clause错误解决办法

    在有些时候有级联关系的数据放在了同一张表中,在写sql语句的时候可能会遇到这样的场景:我要插入两条数据,第一条是父节点,第二条是子节点,关联关系是父节点的自增长id:在写这样的sql语句时有可能就会出 ...

  4. MySQL-8.0.16 的安装与配置

    最近老是安装mysql, 但是由于各个环境下文件不互通,所以感觉笔记还是记录在这里比较方便.以下内容,是对网络上大家的笔记的搜集和整理,并经过自己的实践,记录下来.以便,让大家更好.更快的配置mysq ...

  5. Nginx安装与配置文件nginx.conf详解

    引用“http://ixdba.blog.51cto.com/2895551/790611” 1.安装Nginx在安装Nginx之前,需确保系统已经安装了gcc. openssl-devel. pcr ...

  6. layui列表表单

    列表: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title ...

  7. Vue框架之vuex的使用

    1.首先需要在你的项目目录下安装vuex 终端命令: 2.在全局组件中导入与声明vuex 3.创建store实例对象 let store = new Vuex.store({ state:{ }, m ...

  8. /etc/apt/sources.list 和 /etc/apt/sources.list.d

    转自:大数据云技术基础之Linux源:/etc/apt/sources.list文件 导读 1./etc/apt/sources.list的作用是什么?2.为什么会产生 /etc/apt/source ...

  9. nexus私服搭建及信息配置

    nexus私服搭建及信息配置 下载 登录nexus官网下载nexus安装包https://help.sonatype.com/repomanager2/download/download-archiv ...

  10. P1282 多米诺骨牌[可行性01背包]

    题目来源:洛谷 题目描述 多米诺骨牌有上下2个方块组成,每个方块中有1~6个点.现有排成行的 上方块中点数之和记为S1,下方块中点数之和记为S2,它们的差为|S1-S2|.例如在图8-1中,S1=6+ ...