2013-07-05 87 views
1

我處於一個奇怪的情況。我正在生成按特定類別分組的項目列表。在我的視圖模型中,我將項存儲在ReadOnlyDictionary<string, List<CustomObject>>的實例中,其中CustomObject表示我創建的用於存儲每個列表項的類。該字符串是類別。在我看來,我有一個StackPanel其中<ItemsControl>。該項目的控制有一個ItemTemplate這看起來有點像這樣:Wpf數據模板 - 如何訪問ItemsControl中項目的父項?

<DataTemplate x:Key="DataTemplateName"> 
    <StackPanel> 
     <Separator /> 
     <TextBlock Text="{Binding Key}" /> 
     <ItemsControl ItemsSource="{Binding Value}" /> 
    </StackPanel> 
</DataTemplate> 

的綁定上述工作很大。問題是我不希望第一個項目上面有分隔符。所以我想我需要一個不同的風格的第一個項目。

我試過使用ItemTemplateSelector,但問題是它只能訪問當前項目,所以無法知道它是否在第一個元素上。我也試着做一些像

<Separator 
    Visibility={Binding ShowSeparator, RelativeSource={RelativeSource AncestorType={x:Type CustomObject}}}" /> 

...其中ShowCategories在CustomObject類着眼於ReadOnlyDictionary實例,並表示是否要顯示分隔依賴項屬性。但是當我這樣做時,ShowCategories永遠不會被訪問。我想即使是這樣,它也無法知道哪個項目正在調用它。

所以。我該怎麼辦?

+0

您可以將DataTrigger添加到分隔符樣式,如果選擇了第一個項目,它將摺疊分隔符。 –

回答

0

我會去的MVVM方法:

  1. 有一個CustomObjectViewModel保存在你的字典,而不是你的CustomObject,你CustomObject,因爲它的模式

  2. 在CustomObjectViewModel中有權訪問CustomObjectService(或爲了簡單起見,對字典的引用)。

  3. 在提到的服務,也有類似的方法:

    Public Boolean IsCustomObjectFirst(CustomObjectViewModel vm){..}

    這將很明顯,檢查給定的項目的位置。

  4. 現在只是有一個屬性ShouldDisplaySeperatorCustomObjectViewModel,即會得到它的價值從CustomObjectService.IsCustomObjectFirst(this)

  5. 現在只是用它在你的視圖的定義,它使用類似於:

    視圖定義:

    <DataTemplate x:Key="DataTemplateName"> 
        <StackPanel> 
         <Separator Visibilty="{Binding ShouldDisplaySeperator,Converter={StaticResource BooleanToVisibilityConverter}}" /> 
         <TextBlock Text="{Binding Model.Key}" /> 
         <ItemsControl ItemsSource="{Binding Model.Value}" /> 
        </StackPanel> 
    </DataTemplate> 
    
+0

謝謝!我會試試看! –

+0

沒問題,它解決了你的問題嗎?或者答案需要調整? –

+0

我只是現在有機會嘗試它。我會告訴你。 –

0

您合作如果不需要在虛擬機中添加新的屬性或使用ItemTemplateSelector,則可以這樣做。

我寧願把這個單獨的XAML,因爲它只是查看相關和無關的需要任何邏輯「測試」

因此,一個XAML解決方案是使用ItemsControl.AlternationIndex

東西如:

<ListBox AlternationCount="{Binding RelativeSource={RelativeSource Self}, Path=ItemsSource.Count, Mode=OneWay}"> 
    <ListBox.ItemTemplate> 
    <DataTemplate> 
     <StackPanel> 
     <Separator x:Name="seperator" /> 
     <TextBlock Text="{Binding Key}" /> 
     <ItemsControl ItemsSource="{Binding Value}" /> 
     </StackPanel> 
     <DataTemplate.Triggers> 
     <DataTrigger Binding="{Binding Path=(ListBox.AlternationIndex), 
             RelativeSource={RelativeSource FindAncestor, 
                     AncestorType={x:Type ListBoxItem}}}" 
         Value="0"> 
      <Setter TargetName="seperator" 
        Property="Visibility" 
        Value="Hidden" /> 
     </DataTrigger> 
     </DataTemplate.Triggers> 
    </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

該片段的兩個關鍵部分。

  • 我們指定的ListBox一樣ItemSource.Count,從而生成每個ListBoxItem獨特的AlternationIndexAlternationCount
  • DataTemplate.DataTrigger只是檢查當前項目,看它是否爲AlternationIndex爲0,如果是,則隱藏seperator
相關問題