Changing WPF Listbox SelectedItem text color and highlight/background Color using C#

前端 未结 3 844
天命终不由人
天命终不由人 2020-12-10 18:05

I am trying to change the highlighted(selected) color and the highlighted text color of a wpf listbox at runtime. I have tried creating a style and applying it as follows:

3条回答
  •  时光说笑
    2020-12-10 18:56

    To all the neigh-sayers out there... do not lose hope! it can be done!

    I started off with VSS right-click on the listbox and used every "Edit Template" and "Edit Additional Templates" for each thing available until I found the how these things work.

    You start off quite simply with a list box, bound to MVVM as normal.

    
    
    

    In UserControl or Window Resources set up a few things....

    ListBoxStyle - This styles the main container of the listbox, you can set the borders, margins, padding etc of the main box here. For my example I'm just getting rid of everything to de-style it.

    
        
    
    

    ItemContainerStyle - This is the bit that people say can't be re-styled - it contains the "windows-selector-blue" bar when an item is selected, but fear not this too can be re-styled (merge this UserControl.Resources section in combination with the above one).

    This section is> changing the template of the ItemContainer from whatever it is to a Border, setting a top margin of 3 to pad things out and setting up a style. All we're doing with this style is adding 3px transparent border to the left and right of the item. Then in the Triggers>IsSelected (target of myBorder), changing the border Brush to Red.

    
        
                        
                        
                            
                                
                            
                        
                    
                
            
        
    
    

    ListBoxItemDataTemplate - The next step is to make the item container that displays your data. In my example the YourTextBlockStyler has a trigger on the Text>binding and changes the foreground and background colours of the text. Take note that the foreground and background of the Listbox style are set to transparent, so you have to over ride them in your TextBlock style if you want to see anything.

    
        
            
        
    
    

    Back to the listbox - Now we've set up all the styles and templates in the Resources section we can update the listbox with Style="" ItemContainerStyle="" and ItemTemplate=""

    
    
    

    Then your boring list box will transform magically in to a totally restyled list box with red border selector

    From into

    All without editing a single System.ResourceBrush =]

提交回复
热议问题