C# 组合框选择填充从平面文件读取服务器列表的列表框

C# 组合框选择填充从平面文件读取服务器列表的列表框,c#,wpf,C#,Wpf,我想根据从组合框下拉列表中所做的选择,在平面文件中用服务器列表填充列表框。这是我所拥有的,但它没有填充列表框。。谢谢 private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (ComboBox.SelectedItem.ToString() == "Choice1") { Listbox1.ItemsSou

我想根据从组合框下拉列表中所做的选择,在平面文件中用服务器列表填充列表框。这是我所拥有的,但它没有填充列表框。。谢谢

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (ComboBox.SelectedItem.ToString() == "Choice1")
        {
            Listbox1.ItemsSource = null;
            Listbox1.Items.Clear();
            Listbox1.ItemsSource = File.ReadAllLines(@"C:\temp\serverlist1.txt");
        }
        return;
    }
这是XAML

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <ComboBox x:Name="ComboBox" Grid.Column="0" SelectionChanged="ComboBox_SelectionChanged">
        <ComboBoxItem Content="Choice1"/>
        <ComboBoxItem Content="Choice2"/>
    </ComboBox>
    <ListBox x:Name="Listbox1" Grid.Column="1" />
</Grid>

代码中唯一的错误是,您将ComboBox SelectedItem字符串与“Choice”进行比较,后者永远不会相等。您需要首先将SelectedItem解析为ComboBoxItem,然后将ComboBoxItem的内容与预期的字符串进行比较。下面是演示,

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        if (((ComboBoxItem)comboBox1.SelectedItem).Content.Equals("Choice1"))
            {
            listBox1.ItemsSource = null;
            listBox1.Items.Clear();
            listBox1.ItemsSource = File.ReadAllLines(@"C:\application1\serverlist1.txt");
            }
        return;
        }

代码中唯一的错误是将ComboBox SelectedItem字符串与“Choice”进行比较,而“Choice”永远不会相等。您需要首先将SelectedItem解析为ComboBoxItem,然后将ComboBoxItem的内容与预期的字符串进行比较。下面是演示,

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        if (((ComboBoxItem)comboBox1.SelectedItem).Content.Equals("Choice1"))
            {
            listBox1.ItemsSource = null;
            listBox1.Items.Clear();
            listBox1.ItemsSource = File.ReadAllLines(@"C:\application1\serverlist1.txt");
            }
        return;
        }

也请共享XAML代码。这将简化助手的生活。请共享XAML代码。这将使助手们的生活更轻松。