WPF自動完成控制項

來源:互聯網
上載者:User

代碼:/Files/zhuqil/AutoComplete.zip

介紹:

     在WPF中缺少一個支援自動完成的控制項,最接近的控制項是ComboBox ,它也是實現本篇文章的一個基礎控制項。

背景:

     一個自動完成控制項允許使用者輸入文本的時候,控制項會儘可能的去查詢出一個使用者已經輸入的文本選擇項。最流行的自動完成處理是通過查詢這個控制項當前文本的開頭部分。

它是如何運作:

下面是我們關心的一些ComboBox中的屬性:
  • IsEditable- 這個允許使用者在這個控制項上輸入文本。
  • StaysOpenOnEdit - 這個將強制ComboBox在輸入時保持開啟。
  • IsTextSearchEnabled - 這將使用ComboBox預設的自動完成的行為。
  •  

    我們通過使用上面的屬性結合一個控制延遲查詢的時間,和允許使用者附加新的資料來源的事件,以及一些風格樣式,來實現自動完成控制項。(AutoComplete.xaml.cs檔案中)

     

    使用這個控制項

     

    <Window x:Class="Gui.TestWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ctr="clr-namespace:Gui.Controls"
          Title="Auto Complete Test" 
          Height="200" Width="300" 
          Loaded="Window_Loaded">
        <StackPanel>
            <StackPanel.Resources>
                <ResourceDictionary 
                  Source="/Gui.Controls;component/Styles/AutoComplete.Styles.xaml" />
            </StackPanel.Resources>
            
            <Label>Cities:</Label>
            <ctr:AutoComplete x:Name="autoCities" 
               SelectedValuePath="CityID" DisplayMemberPath="Name" 
               PatternChanged="autoCities_PatternChanged" 
               Style="{StaticResource AutoCompleteComboBox}"
               Delay="500"/> 
            <!-- can also do binding on selected value -->
        </StackPanel>
    </Window>

     

    類似一個combobox,自動完成控制項利用DisplayMemberPath 和SelectValuePath 屬性來綁定具體的資料來源

    /// <summary>
    /// occurs when the user stops typing after a delayed timespan
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="args"></param>
    protected void autoCities_PatternChanged(object sender, 
              Gui.Controls.AutoComplete.AutoCompleteArgs args)
    {
        //check
        if (string.IsNullOrEmpty(args.Pattern))
            args.CancelBinding = true;
        else
            args.DataSource = TestWindow.GetCities(args.Pattern);
    }

     

    我們能利用PatternChanged事件來監聽控制項上當前輸入資料的改變。

    有趣的地方:

        利用MVVM模式能建立一個任何實體的視圖模型,並將其綁定到具有突顯屬性的資料來源上。通過使用樣式,這突顯的部分將顯示在下拉框中。

    說明:

        代碼很簡單,很容易看懂。有任何問題請提出來改正,謝謝!紅色部分是自己加的。

     原文連結:http://www.codeproject.com/KB/WPF/WPF_Autocomplete.aspx

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.