根据ViewModel中存在的属性值在ItemContainerStyleSelector中设置样式

NAG*_*EE 3 wpf mvvm

我想知道您可以根据相应ViewModel中存在的Property值来决定自定义Style Selector类中的样式吗?

要么

有没有办法根据ViewModel中的Property选择ItemContainerstyle?

Anj*_*han 8

是的,ItemsControl提供ItemContainerStyleSelector了这个.可能有两种不同的情况进行选择Style了ItemContainer.

在这个例子中,我们有

public class ViewModel
{ 
   public ObservableCollection<Student> Students { get; set; } 
   public bool IsGood { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
  1. 选择基于主ViewModel(这是不同的ItemsSource).使用Trigger此.

       <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>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 根据属性(例如,名称)选择Student.我们必须在ItemsControl.ItemContainerStyleSelector这里使用.

      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;
            }
        }
    
    Run Code Online (Sandbox Code Playgroud)

    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>
    
    Run Code Online (Sandbox Code Playgroud)