【发布时间】:2011-01-21 06:35:27
【问题描述】:
This other SO question 询问 WPF 中的自动完成文本框。有几个人建造了这些,其中给出的答案之一建议this codeproject article。
但我没有找到任何与 WinForms 自动完成文本框相比的 WPF 自动完成文本框。 codeproject 示例工作,有点,...
...但是
- 它的结构不是可重用的控件或 DLL。这是我需要嵌入到每个应用程序中的代码。
- 它只适用于目录。它没有用于设置自动完成源是否仅为文件系统目录、文件系统文件或 ....etc 的属性。当然,我可以编写代码来执行此操作,但是……我宁愿使用其他人已经编写的代码。
- 它没有设置弹出窗口大小等的属性。
- 有一个弹出列表框显示可能的完成。浏览该列表时,文本框不会更改。在列表框中聚焦时键入字符不会导致文本框更新。
- 将焦点从列表框移开不会使弹出列表框消失。这令人困惑。
所以,我的问题:
*有没有人有免费的 WPF 自动完成文本框可以工作,并提供高质量的 UI 体验?*
回答
我是这样做的:
.0。获取WPF Toolkit
.1。为 WPF 工具包运行 MSI
.2。在 Visual Studio 中,从工具箱(特别是数据可视化组)拖放到 UI 设计器中。在 VS 工具箱中是这样的:
如果您不想使用设计器,请手工制作 xaml。它看起来像这样:
<toolkit:AutoCompleteBox
ToolTip="Enter the path of an assembly."
x:Name="tbAssembly" Height="27" Width="102"
Populating="tbAssembly_Populating" />
...工具包命名空间以这种方式映射:
xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
.3。提供Populating 事件的代码。这是我使用的:
private void tbAssembly_Populating(object sender, System.Windows.Controls.PopulatingEventArgs e)
{
string text = tbAssembly.Text;
string dirname = Path.GetDirectoryName(text);
if (Directory.Exists(Path.GetDirectoryName(dirname)))
{
string[] files = Directory.GetFiles(dirname, "*.*", SearchOption.TopDirectoryOnly);
string[] dirs = Directory.GetDirectories(dirname, "*.*", SearchOption.TopDirectoryOnly);
var candidates = new List<string>();
Array.ForEach(new String[][] { files, dirs }, (x) =>
Array.ForEach(x, (y) =>
{
if (y.StartsWith(dirname, StringComparison.CurrentCultureIgnoreCase))
candidates.Add(y);
}));
tbAssembly.ItemsSource = candidates;
tbAssembly.PopulateComplete();
}
}
它可以正常工作,正如您所期望的那样。感觉很专业codeproject 控件没有出现任何异常。这是它的样子:
Thanks to Matt for the pointer 到 WPF 工具包。
【问题讨论】:
标签: wpf textbox autocomplete