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

转载于:https://www.cnblogs.com/xxxxue/p/11153615.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值