![](/img/trans.png)
[英]How to dynamically add items to ListBox in Windows Phone 7/C#
[英]How to display a dictionary of items in a Listbox on Windows Phone, using C#?
在這里,我打開了一個單詞/定義文本文件。 我對其進行了修剪,將單詞放入newword
,將定義放入newdefn
。 我將其放在字典中,其創建如下:
Dictionary<string, string> d = new Dictionary<string, string>();
我宣布為全球。 由於它位於while(!endofstream)
循環內,因此所有單詞和定義都存儲在該循環中。
我的問題是如何將字典中的值放入listbox
。 我的代碼:
public search()
{
InitializeComponent();
Stream txtStream = Application.GetResourceStream(new
Uri("/PanoramaApp1;component/word.txt", UriKind.Relative)).Stream;
using (StreamReader sr = new StreamReader(txtStream))
{
string jon;
//definition.Text = sr.ReadToEnd();
while (!sr.EndOfStream)
{
jon = sr.ReadLine();
newword = (word.Trim(new Char[] { '-',' ' }));
newdefn = (defn.Trim(new Char[] { '-',' ' }));
d.Add(newword, newdefn);
}
}
}
我現在想在文本框中進行搜索,並將結果顯示在列表框中。 但是我對“文本框選擇已更改”中的部分有疑問。 我在listbox.Items.Add(str);
遇到錯誤listbox.Items.Add(str);
List<string> list = new List<string>(d.Keys);
foreach (string str in list)
{
if (str.StartsWith(searchbox.Text,
StringComparison.CurrentCultureIgnoreCase))
{
listbox.Items.Add(str);
}
}
您必須將Dictionary
設置為ListBox
的ItemsSource
屬性:
yourListBox.ItemsSource = d;
您可以使用項目的DataTemplate
自定義顯示項目的方式。 例如只顯示單詞:
<ListBox Name="yourListBox" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Key}" Tap="Item_Tap" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
要在點擊項目時在MessageBox中顯示定義,可以在事件處理程序中執行以下操作:
private void Item_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var s = sender as TextBlock;
MessageBox.Show(d[s.Text]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.