Change background color of ListView row programmatically (wpf)

前端 未结 6 1810
再見小時候
再見小時候 2020-12-09 20:53

I have a class that populates a ListView by passing a list of objects. The class uses reflection to see the properties of each object in order to generate the ListView. How

6条回答
  •  时光取名叫无心
    2020-12-09 21:19

    After some googling i found out my own solution I am using Listview.ItemsSource and as source i use List Then i can set background of specify ListViewItem in List, and just refresh listview.

    XAML:

     
                    
                        
                            
                            
                            
                            
                            
                        
                    
                
    

    Fill ListView with Items with Gray Background:

        List ITEMS = new List();
        private void button_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 1; i < 20; i++)
            {
                ListViewItem OneItem = new ListViewItem();
                OneItem.Background = Brushes.LightGray;
                OneItem.Content = new Device() { IP = "1.1.1.1", Ping = "30ms", DNS = "XYZ", MAC = "2F:3C:5F:41:F9", Manufacturer = "Intel" };
                ITEMS.Add(OneItem);
                listView.ItemsSource = ITEMS;
            }
            listView.Items.Refresh();
        }
        public class Device
        {
            public string IP { get; set; }
            public string Ping { get; set; }
            public string DNS { get; set; }
            public string MAC { get; set; }
            public string Manufacturer { get; set; }
        }
    

    Create Method for Row Change Color:

        private void ChangeRowColor(int RowIndex,SolidColorBrush NewBackground)
        {
            ITEMS[RowIndex].Background = NewBackground;
            listView.Items.Refresh();
        }
    

    And use it:

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            ChangeRowColor(4, Brushes.Green);
        }
    

提交回复
热议问题