简体   繁体   English

如何获取列表框以显示值C#

[英]How to get listbox to display values C#

Need help trying to display values I have added to a listbox. 需要帮助尝试显示我添加到列表框中的值。 I have researched several ways to add to a listbox. 我研究了几种添加到列表框的方法。 This was the latest attempt of mine, but I can't figure out how to display the "Netflix" and "Hulu". 这是我的最新尝试,但我不知道如何显示“ Netflix”和“ Hulu”。 After debugging, the values are inside the listbox. 调试后,值在列表框中。 I just can't see the text. 我只是看不到文字。

On a side note I am working on this to show a BASIC Observer Pattern. 附带说明一下,我正在努力显示BASIC Observer模式。 To show the changes in the code, I would like to display the results of subscribing to different providers. 为了显示代码中的更改,我想显示订阅不同提供者的结果。 Thanks in advance guys! 在此先感谢大家!

public partial class MainWindow : Window
{
    List<string> myList = new List<string>();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void subscribeToNetflixButton_Click(object sender, RoutedEventArgs e)
    {
        Netflix netflix = new Netflix("Stir Crazy");
        Observer subscriberOne = new Observer();
        netflix.AddObserver(subscriberOne);
        myList.Add("Netflix");
        listBox.Items.Add(myList.ToArray());
    }

    private void subscribeToHuluButton_Click(object sender, RoutedEventArgs e)
    {
        Hulu hulu = new Hulu("Willy Wonka and the Chocolate Factory");
        Observer subscriberTwo = new Observer();
        hulu.AddObserver(subscriberTwo);
        myList.Add("Hulu");
        listBox.Items.Add(myList.ToArray());
    }
}

You should use AddRange with collections not Add : 您应该将AddRange与集合(而非Add

public partial class MainWindow : Window
{
    List<string> myList = new List<string>();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void subscribeToNetflixButton_Click(object sender, RoutedEventArgs e)
    {
        Netflix netflix = new Netflix("Stir Crazy");
        Observer subscriberOne = new Observer();
        netflix.AddObserver(subscriberOne);
        myList.Add("Netflix");
        listBox.Items.AddRange(myList.ToArray());//This line should be changed
    }

    private void subscribeToHuluButton_Click(object sender, RoutedEventArgs e)
    {
        Hulu hulu = new Hulu("Willy Wonka and the Chocolate Factory");
        Observer subscriberTwo = new Observer();
        hulu.AddObserver(subscriberTwo);
        myList.Add("Hulu");
        listBox.Items.AddRange(myList.ToArray());//And this line
    }
}

BTW: If you're using WPF though you have to add your own AddRange (it is not available by default), through looping over the collection inside an extension method for example, or outside if you don't need the functionality many times. 顺便说一句:如果您使用的是WPF,则必须添加自己的AddRange(默认情况下不可用),例如,通过在扩展方法内部循环该集合,或者在不需要多次功能的外部进行循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM