WPF Disable ListBox Selection Workaround

In this example, we will demonstrate how we can disable the WPF listbox selection.
As we all know, that there is no property in ListBox such as "SelectionMode"= None.
So, instead of disabling the listbox selection, we can override the system colors in such a way that , even when the list box is selected, it appears as if the listbox is not selected.
We are overriding the "HighlightBrushKey" and "ControlBrushKey" as Transparent and "HighlightTextBrushKey" as Black. So the background which gets selected will remain transparent and the foreground will turn black.
Here is the source code for the same:

<Grid >
        <Grid.Resources>
             <x:Array x:Key="StringArrayResource" Type="sys:String">
                <sys:String>List Value1</sys:String>
                <sys:String>List Value2</sys:String>
                <sys:String>List Value3</sys:String>
            </x:Array>
        </Grid.Resources>

  <ListBox Grid.Row="0" ItemsSource="{DynamicResource StringArrayResource}">
            <ListBox.Resources>
                    <SolidColorBrush x:Key='{x:Static SystemColors.HighlightBrushKey}' Color='Transparent'/>
                    <SolidColorBrush x:Key='{x:Static SystemColors.HighlightTextBrushKey}' Color='Black'/>
                    <SolidColorBrush x:Key='{x:Static SystemColors.ControlBrushKey}' Color='Transparent'/>
                </ListBox.Resources>        
        </ListBox>
</Grid>

Screenshots:
Before Overriding System Colors:
 After Overriding System Colors:



No comments:

Post a Comment