我一直在搜索WPF中列表视图中的记录/项目/字符串,但没有运气。我刚刚开始WPF,特别是c#。在我的程序中,我有文本框/文本块按钮和列表视图。假设我在列表视图中已经有一条记录。顺便说一下,在列表视图中,我有参考代码列和详细信息。例如,当我在文本框中输入"12345"并单击"搜索"按钮时,如果记录不存在,但如果记录在列表视图中,它会给我一条消息。它会Selected=True;
这是我在 VB.net(不是 WPF)中的代码,我想在 WPF C# 中这样做
For ist As Integer = 0 To LVNewBill.Items.Count - 1
LVNewBill.Items(ist).Selected = False
Next
For i As Integer = 0 To LVNewBill.Items.Count - 1
'If LVNewBill.Items(i).SubItems(0).Text.Contains(str) Then
If LVNewBill.Items(i).Text.Contains(InsertChange) Then
LVNewBill.Items(i).Selected = True
LVNewBill.Items(i).EnsureVisible()
'If the Record Found it will Update
With Me.LVNewBill.SelectedItems(0).SubItems
'.Item(0).Text = txtrefcode.Text
.Item(1).Text = txtdetails.Text
.Item(2).Text = txtperiod.Text
.Item(3).Text = txtduedate.Text
Dim newtxtamt As Double = txtamt.Text
.Item(4).Text = newtxtamt.ToString("###,###,##0.#0")
End With
Else
' add to lvmain
End If
Next
主要方法:
private void init()
{
listView1.Items.Add(new ListViewItem() { Content = "Hi" });
listView1.Items.Add(new ListViewItem() { Content = "Hello"});
listView1.Items.Add(new ListViewItem() { Content = "Buy" });
}
private bool find(string str)
{
foreach (ListViewItem item in listView1.Items)
{
if (item.Content.Equals(str))
{
return true;
}
}
return false;
}
private void select(string str)
{
foreach (ListViewItem item in listView1.Items)
{
if (item.Content.Equals(str))
{
item.IsSelected = true;
}
else
{
item.IsSelected = false;
}
}
}
private void onSelectedClickHandler(object sender, RoutedEventArgs e)
{
if (find(searchTextBox.Text))
{
select(searchTextBox.Text);
}
else
{
MessageBox.Show("Not found");
}
}
我会在这里使用 linq 查询。
var qry = from t in LVNewBill.Items
where t.Text.Contains(InsertChange)
select t;
foreach(var item in qry)
{
item.Selected = true;
item.EnsureVisible();
item.SubItems[1].Text = txtdetails.Text;
item.SubItems[2].Text = txtperiod.Text;
item.SubItems[3].Text = txtduedate.Text;
//Might want to consider TryParse here
double newtxtamt = double.Parse(txtamt.Text);
item.SubItems[4].Text = newtxtamt.ToString("###,###,##0.#0");
}