[英]Search string and select line in WPF listbox C#
in windows form application i do this to find string and select line 在Windows窗体应用程序中,我这样做是要查找字符串并选择行
listBoxGCode.SelectedItems.Clear();
int index = listBoxGCode.FindString(N + e.Value.ToString());
if (index != -1)
{
listBoxGCode.SetSelected(index, true);
}
in WPF i cannot get it to work, I've tried this 在WPF中,我无法使其正常工作,我已经尝试过
int index = listBoxGCode.Items.IndexOf((from ListBoxItem a in listBoxGCode.Items where a.Content.ToString() == "N100" select a).First());
when i run this code i get this message Window 当我运行此代码时,我收到此消息窗口
unable to cast object of "system.string" to type "system.windows.controls.listboxitem" 无法将“ system.string”的对象强制转换为“ system.windows.controls.listboxitem”
do i need to add any code to the .xaml code? 我需要在.xaml代码中添加任何代码吗?
You might have directly added strings into the Items
collections of the ListBox
, so the type of each item in this expression is actually string, instead of ListBoxItem
, this is why you get the InvalidCastException
. 您可能已将字符串直接添加到
ListBox
的Items
集合中,因此此表达式中每个项目的类型实际上是字符串,而不是ListBoxItem
,这就是为什么要获得InvalidCastException
。
from ListBoxItem a in listBoxGCode.Items
To fix this, wrap each string into a ListBoxItem
in XAML. 要解决此问题,请将每个字符串包装到XAML中的
ListBoxItem
中。
<ListBox x:Name="listBoxGCode">
<ListBox.Items>
<ListBoxItem>a</ListBoxItem>
<ListBoxItem>b</ListBoxItem>
<ListBoxItem>c</ListBoxItem>
</ListBox.Items>
</ListBox>
If you want to do this in code behind, you can do it like this 如果要在后面的代码中执行此操作,则可以这样做
listBoxGCode.Items.Add(new ListBoxItem() { Content = "a" });
listBoxGCode.Items.Add(new ListBoxItem() { Content = "b" });
listBoxGCode.Items.Add(new ListBoxItem() { Content = "c" });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.