gpt4 book ai didi

c# - WPF 建议文本框

转载 作者:行者123 更新时间:2023-12-03 10:20:20 27 4
gpt4 key购买 nike

我构建了一个小的 WPF 文本框来检查它的内容是否有效。现在我想实现提供建议的可能性。但不像互联网上弹出建议列表的示例。我正在寻找一个通过选择 TextBox 来实现的示例:


如果有我可以查找的特定名称或您知道的任何示例代码,请告诉我。

最佳答案

在与 WPF 进行了大量的斗争之后,我有一个适用于您的概念证明:

主窗口.xaml

<Window x:Class="Solutions.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"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBox VerticalAlignment="Center" HorizontalAlignment="Center" x:Name="SuggestionBox" Width="200"
/>
</Grid>
</Window>

主窗口.xaml.cs:

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace Solutions
{
public partial class MainWindow : Window
{
private static readonly string[] SuggestionValues = {
"England",
"USA",
"France",
"Estonia"
};

public MainWindow()
{
InitializeComponent();
SuggestionBox.TextChanged += SuggestionBoxOnTextChanged;
}

private string _currentInput = "";
private string _currentSuggestion = "";
private string _currentText = "";

private int _selectionStart;
private int _selectionLength;
private void SuggestionBoxOnTextChanged(object sender, TextChangedEventArgs e)
{
var input = SuggestionBox.Text;
if (input.Length > _currentInput.Length && input != _currentSuggestion)
{
_currentSuggestion = SuggestionValues.FirstOrDefault(x => x.StartsWith(input));
if (_currentSuggestion != null)
{
_currentText = _currentSuggestion;
_selectionStart = input.Length;
_selectionLength = _currentSuggestion.Length - input.Length;

SuggestionBox.Text = _currentText;
SuggestionBox.Select(_selectionStart, _selectionLength);
}
}
_currentInput = input;
}
}
}

下一步是将其转换为用户控件,这样您就可以通过绑定(bind)设置您的建议,无论您如何处理。

关于c# - WPF 建议文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51684857/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com