0

在这里,我打开了一个单词/定义文本文件。我把它修整了,把词放进去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);

 List<string> list = new List<string>(d.Keys);

 foreach (string str in list)
 {
     if (str.StartsWith(searchbox.Text, 
            StringComparison.CurrentCultureIgnoreCase))
     {
         listbox.Items.Add(str);
     }
 }
4

1 回答 1

1

您必须将 设置Dictionary为您的ItemsSource属性ListBox

yourListBox.ItemsSource = d;

您可以使用项目的 a 自定义显示项目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]);
}
于 2013-07-31T11:39:40.303 回答