How to set the Highlight brush to random color

LexiCodes 1 Reputation point

I have this code below that sets the color to random, how to set the selected Listbox item to random??

private void button_Click(object sender, RoutedEventArgs e)
Brush brush = new SolidColorBrush(Color.FromRgb((byte)r.Next(1, 255),
(byte)r.Next(1, 255), (byte)r.Next(1, 233)));
label1.Background = brush;

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,695 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Alex Li-MSFT 1,096 Reputation points

    Welcome to our Microsoft Q&A platform!

    I made a demo,you can try it:

            <Style x:Key="_ListBoxItemStyle" TargetType="ListBoxItem">  
                <Setter Property="Template">  
                        <ControlTemplate TargetType="ListBoxItem">  
                            <Border Name="_Border"  
                                <ContentPresenter />  
                                <Trigger Property="IsSelected" Value="true">  
                                    <Setter TargetName="_Border" Property="Background" Value="{Binding Scb}"/>  
            <ListBox SelectionChanged="ListBox1_SelectionChanged" Name="listBox1"  ItemContainerStyle="{DynamicResource _ListBoxItemStyle}" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto">  
      public partial class MainWindow : Window  
            public MainWindow()  
                this.DataContext = new MyViewModel();  
            private void ListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)  
                this.DataContext = new MyViewModel();  
        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()  
                Scb= new SolidColorBrush(Color.FromRgb((byte)r.Next(1, 255), (byte)r.Next(1, 255), (byte)r.Next(1, 233)));