2011-05-11 36 views
1

ListBox.ItemsSource集合分配然後調整ListBox.ItemTemplate以使日期看起來像我想要的那樣非常方便。WPF中的上下文相關數據綁定

考慮綁定一個簡單的已排序字符串列表。
如果收藏足夠大,引人注目的錨點會派上用場。

這裏是我想要的一個概念:
Wpf Example of a databinding http://bteffective.com/images/Data_Bindining_Example.png

基本上我想第一個字母是不同風格的,如果它不匹配的上一個項目的信。我如何處理我的DataTemplate中的上一個項目?

回答

2

您可能需要將源列表解析爲具有三個屬性的新對象列表:該單詞的第一個字母,該單詞的其餘部分以及指示該條目是否爲「錨點」的布爾值。然後,您的DataTemplate可以是第一個字母的TextBlock,其餘部分是TextBlock。然後,IsAnchor布爾型的樣式觸發器可以更改第一個字母的顏色。

+0

這種方法是比較容易,如果是一個簡單的方法來計算的 「錨」。例如。當數據沒有改變並且在附加的類或依賴屬性的幫助下。 – 2011-05-14 11:58:29

0

另一種方法MultiBinding:我傳遞集合作爲參數,查找前一個元素並檢查第一個字母是否匹配。

如果基礎集合是ObservableCollection<T>和更改,則此方法更容易。由於顯示元素需要查找前一元素(O(n)),所以顯示元素也較慢,因此,顯示元素是O(n^2)

在XAML:

<ListBox x:Name="lbExample" > 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <TextBlock Text="{Binding Converter={StaticResource ResourceKey=first}}"> 
        <TextBlock.Style> 
         <Style TargetType="{x:Type TextBlock}"> 
          <Style.Triggers> 
           <DataTrigger Value="True"> 
            <DataTrigger.Binding> 
             <MultiBinding Converter="{StaticResource prevComparerConverter}"> 
              <Binding /> 
              <Binding RelativeSource="{RelativeSource AncestorType={x:Type ListBox}}" Path="ItemsSource"/> 
             </MultiBinding> 
            </DataTrigger.Binding> 
            <Setter Property="Foreground" Value="Red" /> 
           </DataTrigger> 
          </Style.Triggers> 
         </Style> 
        </TextBlock.Style> 
       </TextBlock> 
       <TextBlock Text="{Binding Converter={StaticResource ResourceKey=rest}}"/> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

而在代碼:

public class PrevComparerConverter : IMultiValueConverter 
{ 
    private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); 
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     var item = (string)values[0]; 
     var col = (ObservableCollection<string>)values[1]; 

     var ind = col.IndexOf(item); 
     var res = true; 
     if (ind > 0 && item.Length > 0) 
     { 
      var prev = col[ind - 1]; 
      if (prev.Length > 0 && char.ToLowerInvariant(prev[0]) == char.ToLowerInvariant(item[0])) 
       res = false; 
     } 
     return res; 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

'first'和'rest'靜態資源是簡單的轉換器,分別返回第一個字母和子串(1)。 – 2011-05-14 11:59:36