我想知道您可以根据相应ViewModel中存在的Property值来决定自定义Style Selector类中的样式吗?
要么
有没有办法根据ViewModel中的Property选择ItemContainerstyle?
是的,ItemsControl提供ItemContainerStyleSelector了这个.可能有两种不同的情况进行选择Style了ItemContainer.
在这个例子中,我们有
public class ViewModel
{
public ObservableCollection<Student> Students { get; set; }
public bool IsGood { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
选择基于主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)根据属性(例如,名称)选择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)| 归档时间: |
|
| 查看次数: |
2906 次 |
| 最近记录: |