Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the style in ItemContainerStyleSelector based on the property value present in ViewModel

Tags:

mvvm

wpf

I want to know Can u decide the style in custom Style Selector class based on Property value present in the corresponding ViewModel??

Or

Is there any way to select the ItemContainerstyle based on the Property in the ViewModel??

like image 586
NAGASREE Avatar asked Sep 12 '25 20:09

NAGASREE


1 Answers

Yes, ItemsControl provides ItemContainerStyleSelector for this. There could be two different scenarios for choosing Style for ItemContainer.

In this example, we have

public class ViewModel
{ 
   public ObservableCollection<Student> Students { get; set; } 
   public bool IsGood { get; set; }
}
  1. Choosing based on main ViewModel (this is different from ItemsSource). Use Trigger for this.

       <ItemsControl.Style>
            <Style TargetType="ItemsControl">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsGood}" Value="True">
                        <Setter Property="ItemContainerStyle" Value="{DynamicResource Style1Key}"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
       </ItemsControl.Style>
    
  2. Choosing based on a property (ex, Name) of Student. We have to use ItemsControl.ItemContainerStyleSelector here.

      public class MyStyleSelector : StyleSelector
        {
            public Style Style1 { get; set; }
            public Style Style2 { get; set; }
    
            public override Style SelectStyle(object item, DependencyObject container)
            {
                Student s = (Student)item;
                if(s.Name == "Gopi")
                    return Style1;
                else
                    return Style2;
            }
        }
    

    XAML

    <Window.Resources>
        <Style x:Key="Style1Key">
            <Setter Property="Control.Opacity" Value="0.3"/>
        </Style>
        <Style x:Key="Style2Key">
            <Setter Property="Control.Opacity" Value="0.7"/>
        </Style>
    </Window.Resources> 
    <ItemsControl ItemsSource="{Binding Students}">
    ...
      <ItemsControl.ItemContainerStyleSelector>
         <local:MyStyleSelector Style1="{StaticResource Style1Key}" Style2="{StaticResource Style2Key}"/>
      </ItemsControl.ItemContainerStyleSelector>  
    ...
    </ItemsControl>
    
like image 135
AnjumSKhan Avatar answered Sep 15 '25 21:09

AnjumSKhan