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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章