2012-10-09 32 views
0

我记得在前一段时间,在MSDN上看到一个关于如何根据对象的类类型更改LitViewItem的样式的示例项目。如何根据项目的类别设置ListViewItem的样式

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

感谢, 汤姆P.

编辑: OK,我不认为我正确地描述了我的问题。让我尝试代码:

public class IOItem 
{ 
} 

public class FileItem : IOItem 
{ 
} 

public class DirectoryItem : IOItem 
{ 
} 

public class NetworkItem : IOItem 
{ 
} 

现在,鉴于上述类,我可以创建更改基于类类型的最终对象的风格?例如:

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

这可能吗?

+0

由于选择使用哪种样式的变量不过是对象的类型..您不需要任何形式的转换器或c#魔法,只需在范围内设置样式,对于您想要更改的类型。 (看到我的回答,这很性感!) – Andy

回答

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; 
    } 
} 
+0

比我的回答更好+1 – Paparazzi

+0

我发誓我只看到了一种XAML解决方案,但是当XMAL第一次出现时,它就回来了。这工作,并做到了我想要的。谢谢您的帮助。 –

0

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

DataTemplateSelector Class

另一种选择是一个接口和接口将反映呼叫属性之一。
然后你可以在XAML中使用模板。

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}" /> 
相关问题