WPF Listview项目按其第一个字符突出显示

时间:2012-11-07 07:59:45

标签: c# wpf

我有一个listview,它从数据库中绑定客户数据。我想要专注于他们的第一个角色。例如,当我从键盘点击“B”时,高亮焦点必须转到名称“第一个字符为”B“的客户。你有什么主意吗?我的listview的XAML在下面。

<ListView x:Name="datalist" ButtonBase.Click="datalist_Click" ContextMenuOpening="datalist_ContextMenuOpening" MouseDoubleClick="datalist_MouseDoubleClick" SelectionChanged="datalist_SelectionChanged"
MouseUp="datalist_MouseUp" PreviewMouseUp="datalist_PreviewMouseUp" > 

2 个答案:

答案 0 :(得分:0)

您可以使用代码here而不是文本框_TextChanged事件使用Window_Keydown事件来捕获按下的键。

而不是:

private void textboxsearch_TextChanged(object sender, TextChangedEventArgs e)
{
    FilterItems(listPerson, textBoxSearch.Text);
}

使用此:

private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    FilterItems(listPerson, e.Key.ToString());
}

答案 1 :(得分:0)

当ListView重点关注时,您可以将行为附加到Listview,如下所示:

System.Windows.Interactivity需要引用) XAML:

<ListView SelectionMode="Multiple">
            <ListViewItem>A Company 1</ListViewItem>
            <ListViewItem>A Company 2</ListViewItem>
            <ListViewItem>A Company 3</ListViewItem>
            <ListViewItem>B Company 1</ListViewItem>
            <ListViewItem>B Company 2</ListViewItem>
            <ListViewItem>C Company 1</ListViewItem>
            <ListViewItem>C Company 2</ListViewItem>
            <ListViewItem>C Company 3</ListViewItem>
            <ListViewItem>D Company 1</ListViewItem>
            <ListViewItem>D Company 2</ListViewItem>
            <ListViewItem>E Company 1</ListViewItem>
            <ListViewItem>F Company 1</ListViewItem>
            <i:Interaction.Behaviors>
                <ListBoxHighlighting:ListViewBehavior />
            </i:Interaction.Behaviors>
        </ListView>

行为:

 public class ListViewBehavior : Behavior<ListView>
    {
        protected override void OnAttached()
        {
            AssociatedObject.KeyDown += OnKeyDown;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.KeyDown -= OnKeyDown;
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            var key = e.Key.ToString();

            AssociatedObject.SelectedItems.Clear();

            foreach (var item in AssociatedObject.Items)
            {
                var i = (item as ListViewItem).Content;
                if(i.ToString().StartsWith(key))
                {
                    AssociatedObject.SelectedItems.Add(item);
                }

            }
        }
    }