UWP中ObservableCollection的使用

在UWP发中我们通常要用到AutoSuggestBox(自动建议框)实现下面的效果

AutoSuggestBox的使用方法详见微软官方文档,这里不再赘述:

https://docs.microsoft.com/zh-cn/windows/uwp/controls-and-patterns/auto-suggest-box

这里我对AutoSuggestBox的XAML定义为:

<AutoSuggestBox x:Name="UserName"
                VerticalAlignment="Center"
                HorizontalAlignment="Center"
                Margin="0,20,0,0"
                Width="240"
                PlaceholderText="用户名"
                MaxSuggestionListHeight="260"
                TextChanged="UserNameBox_TextChanged"
                QuerySubmitted="UserName_QuerySubmitted" />

cs代码为:

    public sealed partial class RegisterView : UserControl
    {
        private ObservableCollection<String> suggestions;//自动建议集

        public RegisterView()
        {
            this.InitializeComponent();
            suggestions = new ObservableCollection<string>();//新建自动建议集
        }

        private void UserNameBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
        {
            string name = sender.Text;
            if (name.IndexOf("@") > -1 || name == "")
            {
                suggestions.Clear();//用户已输入@
            }
            else
            {
                suggestions.Clear();
                suggestions.Add(name + "@qq.com");
                suggestions.Add(name + "@outlook.com");
                suggestions.Add(name + "@126.com");
                suggestions.Add(name + "@gmail.com");
                suggestions.Add(name + "@foxmail.com");
                sender.ItemsSource = suggestions;//用户未输入@
            }
        }

        private void UserName_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
        {
            if (args.ChosenSuggestion != null)
                sender.Text = args.ChosenSuggestion.ToString();
            else
                sender.Text = sender.Text;
        }
    }

当ObservableCollection<T>被修改时,系统会自动通知绑定该ObservableCollection<T>的控件做相应修改,因此十分方便

代码中

name.IndexOf(“@”) > -1

是用来判断@是否输入的,如果没有该判断,则会造成用户输入完邮箱地址,程序还会继续建议的尴尬