SelectStyle Method
Collapse the table of content
Expand the table of content

StyleSelector.SelectStyle Method (Object, DependencyObject)


When overridden in a derived class, returns a Style based on custom logic.

Namespace:   System.Windows.Controls
Assembly:  PresentationFramework (in PresentationFramework.dll)

public virtual Style SelectStyle(
	object item,
	DependencyObject container


Type: System.Object

The content.

Type: System.Windows.DependencyObject

The element to which the style will be applied.

Return Value

Type: System.Windows.Style

Returns an application-specific style to apply; otherwise, null.

To create a StyleSelector that applies a style based on custom logic, create a subclass of the StyleSelector class and implement the SelectStyle method.

The following example shows how to define a StyleSelector that defines a Style for a row. This example defines the Background color according to the row index.

public class ListViewItemStyleSelector : StyleSelector
    public override Style SelectStyle(object item, 
        DependencyObject container)
        Style st = new Style();
        st.TargetType = typeof(ListViewItem);
        Setter backGroundSetter = new Setter();
        backGroundSetter.Property = ListViewItem.BackgroundProperty;
        ListView listView = 
              as ListView;
        int index = 
        if (index % 2 == 0)
            backGroundSetter.Value = Brushes.LightBlue;
            backGroundSetter.Value = Brushes.Beige;
        return st;

The following example shows how to define a ResourceKey for the StyleSelector. The namespc prefix maps to a CLR namespace and the corresponding assembly where the StyleSelector is defined. For more information, see XAML Namespaces and Namespace Mapping for WPF XAML.

<namespc:ListViewItemStyleSelector x:Key="myStyleSelector"/>

The following example shows how to set the ItemContainerStyleSelector property of a ListView to this StyleSelector resource.

      ItemsSource="{Binding Source={StaticResource EmployeeData}, 
      ItemContainerStyleSelector="{DynamicResource myStyleSelector}" >      
      <GridViewColumn DisplayMemberBinding="{Binding XPath=FirstName}" 
                      Header="First Name" Width="120"/>
      <GridViewColumn DisplayMemberBinding="{Binding XPath=LastName}" 
                      Header="Last Name" Width="120"/>
      <GridViewColumn DisplayMemberBinding="{Binding XPath=FavoriteCity}" 
                      Header="Favorite City" Width="120"/>

For an example of how to create a selector to choose a defined style resource, see the implementation of DataTemplateSelector.SelectTemplate, which allows you to use custom logic to select a DataTemplate, based on a similar concept.

.NET Framework
Available since 3.0
Return to top
© 2015 Microsoft