2011-10-03 61 views
1

我有一個類繼承ListBox和ListBoxItems自定義ControlTemplate。 如果條件爲真,我想更改ListBoxItems背景。我試圖爲此使用DataTrigger。我不想檢查ListBoxItems上下文對象中的條件,我想在繼承的ListBox類中檢查它。自定義模板listboxitem觸發器綁定到列表框

問題是如何在ControlTemplate中將Trigger綁定到ListBox屬性,何時需要爲運行時的每個ListBoxItem決定正確的值?

<Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="ListBoxItem"> 
        <Border Name="bd"> 
         <TextBlock Name="lbl" Text="{Binding Path=DataChar}" FontWeight="ExtraBold" FontSize="15" Margin="5"/> 
        </Border> 
        <ControlTemplate.Triggers> 
         <DataTrigger Binding="{Binding RelativeSource={ RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}, Path=IsSymbolExists}" Value="True"> 
          <Setter TargetName="bd" Property="Background" Value="Yellow" /> 
         </DataTrigger> 
        </ControlTemplate.Triggers> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 


public class CustomListBox : ListBox 
{ 
... 
    public bool IsSymbolExists 
    { 
      if(/*condition is true for the ListBoxItem*/) 
       return true; 
      return false; 
    } 
} 

回答

1

好吧首先提出幾點建議......

請問您的自定義列表框控件具有只有新特性(IsSymbolExists等),並沒有真正的行爲。如果是這樣,請聲明爲Attached Properties

其次,當該值IsSymbolExists成爲一個ListBox ALL其項目將成爲由黃色邊框高亮單獨真。這看起來不像一個精心設計的用戶界面行爲。對不起,如果這對你來說有點苛刻!

另外從綁定角度看,DataChar屬性看起來像基於數據上下文的屬性,即來自某個模型。如果是這樣,則其綁定必須通過ItemTemplate下的ListBox而不是TextBlock下的ControlTemplateListBoxItem完成。而出於完全相同的原因,DataTrigger將無法​​在ControlTemplate中正常工作。

他們將在ItemTemplate中正常工作。

所以總結一下,需要修正這樣你的代碼...

  1. 可以擺脫CustomListBox。創建一個名爲MyListBoxBehavior.IsSymbolExists的布爾附加屬性。將它附加到你的ListBox。

  2. 你應該擺脫ListBoxItemControlTemplate

,在由該列表框取helpm ......(這段代碼不會編譯,因爲它是):-)

<ListBox local:MyListBoxBehavior.IsSymbolExists="{Binding WhateverBoolean}" 
      ItemsSource="{Binding WhateverCollection}"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <Border> 
       <Border.Style> 
        <Style TargetType="{x:Type Border}"> 
         <Style.Triggers> 
         <DataTrigger 
           Binding="{Binding 
              RelativeSource={RelativeSource 
               Mode=FindAncestor, 
               AncestorType={x:Type ListBox}}, 
             Path=local:MyListBoxBehavior.IsSymbolExists}" 
           Value="True"> 
          <Setter Property="Background" Value="Yellow" /> 
         </DataTrigger> 
         </Style.Triggers> 
        </Style> 
       </Border.Style> 
       <TextBlock Name="lbl" 
          Text="{Binding Path=DataChar}" 
          FontWeight="ExtraBold" 
          FontSize="15" 
          Margin="5"/> 
       </Border> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 

希望這有助於。

相關問題