如何在WPF列表框中使用突出显示实现子字符串搜索/过滤?

时间:2010-08-06 04:59:25

标签: wpf listbox

民间,

我正在编写一个小型WPF Windows应用程序,它具有绑定到任务类型对象的列表框。我需要能够通过TaskName搜索和缩小任务列表。缩小选择范围不是问题,但是对您键入的匹配字符加粗以缩小选择范围。例如,如果我得到任务“派对”和“绘画”,输入“P”和“A”应分别加粗字符。

正如您将看到我的初始实现(下面的MainWindow_KeyDown方法)工作得很好,没有DataTemplate,只有ListBox中的ListBoxItems。如何使用DataTemplates实现相同的行为?

这是我的数据模板,Task类和搜索实现。

谢谢, Helaya

<DataTemplate DataType="{x:Type Model:Task}">
    <Grid x:Name="grid1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="40"/>
            <ColumnDefinition Width="140"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0" Name="t1" Text="*" Padding="0,5" HorizontalAlignment="Left" VerticalAlignment="Center" TextWrapping="Wrap"></TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="0" Name="TaskName" Text="{Binding TaskName}" Padding="0,5" HorizontalAlignment="Left" VerticalAlignment="Center" TextWrapping="Wrap"></TextBlock>            
    </Grid>
</DataTemplate>

public class Task
{
    public string TaskName { get; set; }
    public string Description { get; set; }
    public string Priority { get; set; }
}

    private StringBuilder filterText = new StringBuilder();    

    void MainWindow_KeyDown(object sender, KeyEventArgs e)
    {
        string key = null;

        if (e.Key != Key.Back)
        {
            key = e.Key.ToString();
            filterText.Append(key);
        }
        else
        {
            if (filterText.Length > 0)
                filterText.Remove(filterText.Length - 1, 1);
        }

        foreach (ListBoxItem item in listBox1.Items)
        {
            int index = 0;
            TextBlock textblock = (TextBlock)item.Content;
            string str = textblock.Text;

            if ((index = str.IndexOf(filterText.ToString(), StringComparison.CurrentCultureIgnoreCase)) != -1)
            {
                textblock.Text = null;
                Bold b = new Bold();
                b.Inlines.Add(new Run(str.Substring(index, filterText.Length)));
                textblock.Inlines.Add(b);

                if (str.Length > filterText.Length)
                    textblock.Inlines.Add(str.Substring(filterText.Length));
            }
        }
    }

0 个答案:

没有答案