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,783 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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;
}
}
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" });
}
Thanks.