如何根据项的类设置ListViewItem的样式

时间:2012-10-09 15:02:38

标签: wpf

我记得,前一段时间,在MSDN上看到一个例子,说明如何根据该项目中对象的类类型更改LitViewItem的样式。

有人能指出我这个例子的方向还是喜欢它?我正在转换文件管理器,我很乐意使用这种方法。

谢谢, 汤姆P。

编辑: 好吧,我认为我没有正确描述我的问题。让我试试代码:

public class IOItem
{
}

public class FileItem : IOItem
{
}

public class DirectoryItem : IOItem
{
}

public class NetworkItem : IOItem
{
}

现在,根据上面的类,我可以根据最终对象的类类型创建一个更改的Style吗?例如:

<Style TargetType="{x:Type FileItem}">
    <Setter Property="Background" Value="Red" />
</Style>
<Style TargetType="{x:Type DirectoryItem}">
    <Setter Property="Background" Value="Green" />
</Style>

这可能吗?

3 个答案:

答案 0 :(得分:4)

您需要创建StyleSelector并将其分配给ItemContainerStyleSelector属性。在选择器中,只需根据项目的类型选择一种样式。

class MyStyleSelector : StyleSelector
{
    public override Style SelectStyle(object item, DependencyObject container)
    {
        if (item is FileItem)
            return Application.Current.Resources["FileItemStyle"];
        if (item is DirectoryItem)
            return Application.Current.Resources["DirectoryItemStyle"];
        return null;
    }
}

答案 1 :(得分:0)

我认为你可以使用模板选择器。

DataTemplateSelector Class

另一个选项是界面,界面中的一个属性将反映该调用 然后你可以在XAML中使用模板。

答案 2 :(得分:0)

您可以随时将类类型的样式放在您正在使用的List控件的资源集合中,它们将覆盖您设置的任何全局样式。

<ListView ItemsSource="{Binding Elements}">
        <ListView.Resources>

          <Style TargetType="{x:Type TextBlock}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type TextBlock}">
                            <Rectangle Fill="Green" Width="100" Height="100"/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>

           <Style TargetType="{x:Type Button}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Rectangle Fill="Red" Width="100" Height="100"/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>


        </ListView.Resources>
    </ListView>

如果您想要多个列表控件来包含这些特定的类样式,那么为列表控件创建一个样式,并在其资源旁边包含特定于类型的样式。

  <Window.Resources>

        <Style x:Key="myListStyle" TargetType="{x:Type ListView}">
            <Style.Resources>
                <Style TargetType="{x:Type Button}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type Button}">
                                <Rectangle Fill="Red" Width="100" Height="100"/>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </Style.Resources>
        </Style>

    </Window.Resources>
    <ListView ItemsSource="{Binding Elements}" Style="{StaticResource myListStyle}" />
相关问题