2012-10-09 29 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}" /> 
相關問題