Tuesday, October 25, 2016

using WPF Toolkit autocomplete

To install WPF Toolkit, run the following command in the Package Manager Console:

PM> Install-Package WPFToolkit

or

PM> Install-Package DotNetProjects.Wpf.Toolkit

MainWindow.xaml:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        xmlns:toolkit1="http://schemas.microsoft.com/wpf/2008/toolkit"
        xmlns:toolkit2="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <toolkit1:DatePicker Width="100" Height="32" Margin="10,38,407,249"></toolkit1:DatePicker>
        <toolkit2:AutoCompleteBox x:Name="MyAC" Margin="10,75,0,0"
                         VerticalAlignment="Top"
                         HorizontalAlignment="Left"
                         Width="150"
                         ItemsSource="{Binding Collection}"
                         Height="23"
                         ValueMemberPath="DealerName"
                         SelectionChanged="MyAC_SelectionChanged"
                         >
                            <toolkit2:AutoCompleteBox.ItemTemplate>
                                <DataTemplate >
                                    <StackPanel Orientation="Horizontal" Width="300">
                                        <Label Content="{Binding IDDealer}" Width="100" Background="Black" Foreground="White"/>
                                        <Label Content="{Binding DealerName}" FontStyle="Italic" Foreground="DarkGray" />
                                    </StackPanel>
                                </DataTemplate>
                            </toolkit2:AutoCompleteBox.ItemTemplate>
        </toolkit2:AutoCompleteBox>
        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="301,75,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
    </Grid>
</Window>

Note: if you are using "DotNetProjects.Wpf.Toolkit" instead of "WPFToolkit", the xml namespace should be:

        xmlns:toolkit1="clr-namespace:System.Windows.Controls;assembly=WPFToolkit"
        xmlns:toolkit2="clr-namespace:System.Windows.Controls;assembly=DotNetProjects.Input.Toolkit"


MainWindow.cs:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //public ObservableCollection<Dealer> DealerNameArr = new ObservableCollection<Dealer>();
        //public List<Dealer> DealerNameArr = new List<Dealer>();

        public MainWindow()
        {
            InitializeComponent();

            //this.DealerNameArr.Add(new Dealer() { IDDealer = 0, DealerName = "Dealer 0"});
            //this.DealerNameArr.Add(new Dealer() { IDDealer = 1, DealerName = "Dealer 1"});
            //this.DealerNameArr.Add(new Dealer() { IDDealer = 2, DealerName = "Dealer 2"});

            //MyAC.ItemsSource = DealerNameArr;

            //this.MyAC.PreviewKeyDown += new KeyEventHandler( (a, b) =>
            this.MyAC.Populating += new PopulatingEventHandler((a, b) =>
            {
                switch (b.Key)
                {
                    case Key.Delete:
                    case Key.Back:
                    case Key.Up:
                    case Key.Down:
                    case Key.Left:
                    case Key.Right:
                    case Key.Home:
                    case Key.End:
                        return;
                }

                string jsonStr = AjaxV1("https://erp.local:8443/CN/Demo1?term=" + ((AutoCompleteBox)a).Text + ConvertKeyToChar(b.Key));
                List<Dealer> DealerNameArr = new List<Dealer>();

                iojson i = new iojson();
                i.Decode(jsonStr);
                i.GetObjFromArr(0, DealerNameArr);

                MyAC.ItemsSource = DealerNameArr;
                //this.MyAC.ItemsSource.IsDropDownOpen = true;
            }
            );
        }

        public static char ConvertKeyToChar(Key key)
        {
            return Convert.ToChar(KeyInterop.VirtualKeyFromKey(key));
        }

        public static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public string AjaxV1(string uri)
        {
            try
            {
                // TODO: this is a temporary remove SSL ceritficate check solution. Please comment out this line in production.
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

                Debug.WriteLine("uri: " + uri);

                var httpClient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate });
                var response = httpClient.GetAsync(uri).Result;

                // will throw an exception if not successful
                response.EnsureSuccessStatusCode();

                string jsonStr = response.Content.ReadAsStringAsync().Result;

                Debug.WriteLine("JSON: " + jsonStr);

                //return await Task.Run(() => JsonObject.Parse(content));
                //return await Task.Run(() => content);
                //return response.Content.ReadAsStringAsync();
                return jsonStr;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return "{Status:false}";
            }
        }

        private void MyAC_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var item = ((AutoCompleteBox)sender).SelectedItem;
            Dealer d = (Dealer)item;
            textBlock.Text = d.DealerName + "_" + d.IDDealer;
        }
    }

    public class Dealer
    {
        public int IDDealer { get; set; }
        public string DealerName { get; set; }
    }
}

iojson.cs:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication1
{
    class iojson
    {
        public bool Status { get; set; }
        public List<object> ErrArr { get; set; }
        public int ErrCount { get; set; }
        public List<object> ObjArr { get; set; }
        public Dictionary<string, object> ObjMap { get; set; }

        public object GetObjFromArr(int k, object obj)
        {
            if (k < 0 || k >= this.ObjArr.Count)
            {
                return null;
            }

            var jsonRaw = this.ObjArr[k];

            if (obj == null)
            {
                return jsonRaw;
            }

            populateObj(obj, jsonRaw.ToString());
            return obj;
        }

        public object GetObjFromMap(string k, object obj)
        {
            var jsonRaw = this.ObjMap[k];

            if (obj == null)
            {
                return jsonRaw;
            }

            populateObj(obj, jsonRaw.ToString());
            return obj;
        }

        public string Encode()
        {
            return JsonConvert.SerializeObject(this);
        }

        public void Decode(string jsonStr)
        {
            populateObj(this, jsonStr);
        }

        public error populateObj<T>(T obj, string jsonStr)
        {
            var serializer = new JsonSerializer();

            using (var reader = new StringReader(jsonStr))
            {
                serializer.Populate(reader, obj);
            }

            return null;
        }
    }

    public struct ObjErr
    {
        public object obj;
        public error err;
    }

    public class error
    {
        public string S { get; set; }

        public void New(string s)
        {
            this.S = s;
        }

        public string Error()
        {
            return this.S;
        }
    }
}

Reference:

https://www.nuget.org/packages/WPFToolkit/

https://www.nuget.org/packages/DotNetProjects.Wpf.Toolkit/

https://github.com/dotnetprojects/WpfToolkit/blob/master/WpfToolkit/Samples/AutoCompleteBox/AutoCompleteBoxSample.xaml

No comments: