Setting the style in ItemContainerStyleSelector ba

2019-05-12 17:59发布

问题:

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??

回答1:

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>
    


标签: wpf mvvm