WELCOME TO JASWINDER BLOG
Sunday, 29 May 2011
Highlighting selected item of the List Control in WPF.
In my last WPF assignment, I used data template to bind my data source with ListBox Control .Upon successfully binding data source with ListBox Control, when I select an item form a listbox control, I notice that highlighted color of the selected item in the ListBox was same as system default color. But, I want the color of selected item should be different from default color which makes a difference between selected and unselected item of the control.
So, I found that this can be done by using ItemContainerStyle property which is available in List Control. The ItemContainerStyle is responsible for the overall look of the List Control (ListBox Control in my case).
I attached ItemContainerStyle property like this:
<ListBox ItemContainerStyle="{StaticResource myContainerStyle}">
Here "myContainerStyle" is the name of the style which handles the selected item in the ListBoxItem.Then I defined the code for myContainerStyle like this:
<Style x:Key="myContainerStyle" TargetType="myListBoxItem"> <Setter Property="FocusVisualStyle" Value="{x:Null}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="myListBoxItem">
<Border
Name="Border"
Padding="2"
SnapsToDevicePixels="true">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="Background" Value="Teal"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
In the above code ,note the selected portion where I defined the "IsSelected Property" in the trigger.When ever user select the item from the list ,this trigger will fire and change the background color of the selected item to specified color(in this case it is Teal)
So,the final code for my ListBox control become:
HorizontalAlignment="Left"
ItemTemplate="{StaticResource myDataTemplate}"
ItemsSource="{Binding}"
ItemContainerStyle="{StaticResource myContainerStyle }" >
</ListBox>
Subscribe to:
Posts (Atom)