Listbox add item makes logic not work

LexiCodes 1 Reputation point
2020-04-09T08:22:24.59+00:00

I have a listbox that has 3 items at design time, my logic works, but if I add a button that adds 100 items at run time it does NOT.
I am trying to switch the color of the selection to a different colors with a case statement.

 public int caseSwitch { get; private set; }

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MyViewModel(caseSwitch);

        }

        private void ListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.DataContext = new MyViewModel(caseSwitch);
        }

        private void label1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            caseSwitch = 1;
        }






    public class MyViewModel : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler PropertyChanged;

    Random r = new Random();
    private SolidColorBrush _scb = new SolidColorBrush();
    public SolidColorBrush Scb

    {
    get { return _scb; }
    set { _scb = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Scb")); }
    }



    public MyViewModel(int caseSwitch)
    {
    switch (caseSwitch)
    {
    case 1:
    Scb = new SolidColorBrush(Color.FromRgb((byte)r.Next(1, 255), (byte)r.Next(1, 255), (byte)r.Next(1, 233)));

    //Console.WriteLine("Case 1");
    break;

    case 2:
    Scb = new SolidColorBrush(Color.FromRgb(255, 160, 122));
    break;


    default:
    Scb = new SolidColorBrush(SystemColors.HighlightBrush.Color);
    break;

    }

    }
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,670 questions
0 comments No comments
{count} votes

6 answers

Sort by: Most helpful
  1. Alex Li-MSFT 1,096 Reputation points
    2020-04-15T06:57:58.653+00:00

    Welcome to our Microsoft Q&A platform!

    continue this case:how-to-set-the-highlight-brush-to-random-color.html

    I guess that your issue is wrong to add item,see the difference:

      private void Button_Click(object sender, RoutedEventArgs e)
             {
                 listBox1.Items.Add(4);
             }
     
             private void Button_Click_1(object sender, RoutedEventArgs e)
             {
                 listBox1.Items.Add(new ListBoxItem() { Content = "5" });
             }
    

    7437-1.gif

    Thanks.