【问题标题】:Unable to add text suggestion from a file to my textbox in C#无法将文件中的文本建议添加到 C# 中的文本框
【发布时间】:2016-06-06 02:49:31
【问题描述】:

我正在制作一个通用 Windows 应用程序,其中包括将文本插入文本框。我希望我的应用程序建议将文件中的文本插入到文本框中。但我找不到那个属性。我已经通过 XAML 标记在 MainPage.xaml 中添加了文本框。我相信 WPF API 中有此操作的属性。我只是不确定我是否可以在 UWP 中做到这一点。

【问题讨论】:

  • 你想做出像AutoSuggestBox 这样的TextBox 行为吗?
  • @GraceFeng-MSFT 我不知道 AutoSuggestBox。所以,我想让文本框表现得像 AutoSuggestBox。

标签: c# xaml textbox windows-10-universal


【解决方案1】:

我建议对 UWP 使用 AutoSuggestBox 控件。一旦用户开始输入文本,自动建议结果列表就会自动填充。结果列表可以出现在文本输入框的上方或下方。

<AutoSuggestBox PlaceholderText="Search" QueryIcon="Find" Width="200"
            TextChanged="AutoSuggestBox_TextChanged"
            QuerySubmitted="AutoSuggestBox_QuerySubmitted"
            SuggestionChosen="AutoSuggestBox_SuggestionChosen"/>


private void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
    // Only get results when it was a user typing, 
    // otherwise assume the value got filled in by TextMemberPath 
    // or the handler for SuggestionChosen.
    if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
    {
        //Set the ItemsSource to be your filtered dataset
        //sender.ItemsSource = dataset;
    }
}


private void AutoSuggestBox_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
{
    // Set sender.Text. You can use args.SelectedItem to build your text string.
}


private void AutoSuggestBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
    if (args.ChosenSuggestion != null)
    {
        // User selected an item from the suggestion list, take an action on it here.
    }
    else
    {
        // Use args.QueryText to determine what to do.
    }
}

这里是 GitHub 存储库的 link,以获取完整的 UI 基础示例。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    这可能不适用于 UAP,但对于 WPF,有一个技巧可以允许“下拉建议列表”。您可以用组合框替换文本框,并在用户键入时填充它的项目。这可以通过像这样进行绑定来实现:

    Text={ Binding Path=meCurrentValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }
    
    ItemsSource={Binding Path=meFilteredListOfSuggestions, Mode=TwoWay }
    

    然后在您的视图模型中,您可以简单地执行以下操作:

    public string meCurrentValue
    {
    get { return _mecurrentvalue; }
    set { 
    _mecurrentvalue = value;
    updateSuggestionsList();
    NotifyPropertyChanged("meCurrentValue");
    NotifyPropertyChanged("meFilteredListOfSuggestions"); // notify that the list was updated
    ComboBox.Open(); // use to open the combobox list
    }
    
    public List<string> meFilteredListOfSuggestions
    {
    get{return SuggestionsList.Select( e => e.text.StartsWith(_mecurrentvalue));}
    }
    

    编辑: 请记住将组合框的可编辑值设置为 TRUE,这样它就会像普通的文本框一样工作。

    【讨论】:

      猜你喜欢
      • 2012-11-03
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 2021-08-17
      • 1970-01-01
      相关资源
      最近更新 更多