【问题标题】:Search string and select line in WPF listbox C#在 WPF 列表框中搜索字符串并选择行 C#
【发布时间】:2017-04-30 08:41:03
【问题描述】:

在 Windows 窗体应用程序中,我这样做是为了查找字符串并选择行

            listBoxGCode.SelectedItems.Clear();
            int index = listBoxGCode.FindString(N + e.Value.ToString());              
            if (index != -1)
            {
                listBoxGCode.SetSelected(index, true);

            }

在 WPF 中我无法让它工作,我已经尝试过这个

int index = listBoxGCode.Items.IndexOf((from ListBoxItem a in listBoxGCode.Items where a.Content.ToString() == "N100" select a).First());

当我运行此代码时,我会收到此消息窗口

无法将“system.string”的对象转换为类型“system.windows.controls.listboxitem”

我需要在 .xaml 代码中添加任何代码吗?

【问题讨论】:

    标签: c# wpf xaml listbox


    【解决方案1】:

    您可能已经将字符串直接添加到ListBoxItems 集合中,因此此表达式中每个项目的类型实际上是字符串,而不是ListBoxItem,这就是您得到InvalidCastException 的原因。

    from ListBoxItem a in listBoxGCode.Items
    

    要解决此问题,请将每个字符串包装成 XAML 中的 ListBoxItem

    <ListBox x:Name="listBoxGCode">
        <ListBox.Items>
            <ListBoxItem>a</ListBoxItem>
            <ListBoxItem>b</ListBoxItem>
            <ListBoxItem>c</ListBoxItem>
        </ListBox.Items>
    </ListBox>
    

    如果你想在后面的代码中这样做,你可以这样做

    listBoxGCode.Items.Add(new ListBoxItem() { Content = "a" });
    listBoxGCode.Items.Add(new ListBoxItem() { Content = "b" });
    listBoxGCode.Items.Add(new ListBoxItem() { Content = "c" });
    

    【讨论】:

    • 谢谢。我试一试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多