{A}{S0}简介 If identical, then use the
{A2}我写了如何在Microsoft Outlook中搜索灵感。想象一下,你有一个WPF应用程序中的ListView和您正在寻找一个在个别项目的文本。这将是有益的,突出显示文本的。在本演示中使用的代码可以调整它的地方适当使用TextBox控件显示和突出显示的文本。背景
这是假设你有C#和WPF的基本知识。此应用程序是用来代替文字TextBlock控制项,内联的属性和类的运行,通过它我们可以改变文本属性(如前景,背景,字号等)的财产。使用代码
创建一个ListView和TextBlock搜索。在ListView的即时搜索添加一个TextBox的TextChanged事件。<DockPanel LastChildFill="True">
<StackPanel HorizontalAlignment="Left" DockPanel.Dock="Top">
<Label Name="labelSearch" Content="Search"/>
<TextBox Name="textboxsearch" Width="309"
TextChanged="textboxsearch_TextChanged"
>
</TextBox>
</StackPanel>
<ListView Name="listview" Width="310" DockPanel.Dock="Top"
HorizontalAlignment="Left" FontWeight="Bold" FontSize="16" AlternationCount="2"
ItemContainerStyle="{StaticResource AlternateItemStyle}">
<ListView.View>
<GridView>
<GridViewColumn Header="First Name"
DisplayMemberBinding="{Binding Path=FirstName}">
</GridViewColumn>
<GridViewColumn Header="Last Name"
DisplayMemberBinding="{Binding Path=LastName}">
</GridViewColumn
</GridView>
</ListView.View>
</ListView>
</DockPanel>
使用TextChanged事件,发现所有的递归方法FindListViewItem ListViewItem的项目。 VisualTreeHelper类GetChildrenCount将带来数儿童对象。{C}
如果DependecyObject类型的ListViewItem,使用递归的方法HighlightText TextBlock对象中的ListViewItem查找{A3}private void HighlightText(Object itx)
{
if (itx != null)
{
if (itx is TextBlock)
{
..
}
else
{
...
}
}
return;
}
else
{
...
}
}
}
如果对象是TextBlock的类型,创建一个新的实例正则表达式。
(参数RegExOptions.IgnoreCase忽略大写和小写字母。)
插入括号,你将达到进入该领域的文本的分工,这将包括在搜索文本。 regex = new Regex("(" + textboxsearch.Text + ")", RegexOptions.IgnoreCase);
在TextBlock中的文字分割成一个字符串数组援助RegEx.Split。清除与Inlines.Clear原来的文本。tb.Inlines.Clear();
,并再次在foreach循环,创造比较RegEx.Match的搜索字词字段表达式的文本。foreach (var item in substrings)
{
if (regex.Match(item).Success)
?/pre>
Run
class, create new Inline element, add text, change the background color, and add text to TextBlock
with Inlines.Add
methods. Otherwise, just add text.Run runx = new Run(item);
runx.Background = Brushes.Red;
tb.Inlines.Add(item);
全面的背景改变文本的代码:{A4}foreach (var item in substrings)
{
if (regex.Match(item).Success)
{
Run runx = new Run(item);
runx.Background = Brushes.Red;
tb.Inlines.Add(runx);
}
else
{
tb.Inlines.Add(item);
}
}
现在我们可以启动该项目,并尝试搜索。结论
此应用程序不创建任何特殊的效果,当您突出显示文本,但我认为它可以作为一个灵感。
我希望你发现它有用和感谢阅读。历史8月20日,2010年:战后初期|一月Vilášek