2008-09-28 108 views
83

我需要根據項目是否被選中來更改列表框中項目的DataTemplate(選擇時顯示不同/更多信息)。如果選擇更改ListBox項目的WPF DataTemplate

當單擊有問題的列表框項目(僅通過Tab鍵)時,DataTemplate(StackPanel)中的頂部元素無法獲得GotFocus/LostFocus事件,並且我不知道該如何處理。

回答

167

最簡單的方法是爲「ItemContainerStyle」提供模板,而不是「ItemTemplate」屬性。在下面的代碼中,我創建了兩個數據模板:一個用於「未選中」和一個用於「已選」狀態。然後,我爲「ItemContainerStyle」創建一個模板,它是包含該項目的實際「ListBoxItem」。我將默認的「ContentTemplate」設置爲「Unselected」狀態,然後提供一個觸發器,在「IsSelected」屬性爲true時將模板換掉。 (注:我身後設置「的ItemsSource」屬性中的代碼串進行簡單的列表)

<Window.Resources> 

<DataTemplate x:Key="ItemTemplate"> 
    <TextBlock Text="{Binding}" Foreground="Red" /> 
</DataTemplate> 

<DataTemplate x:Key="SelectedTemplate"> 
    <TextBlock Text="{Binding}" Foreground="White" /> 
</DataTemplate> 

<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle"> 
    <Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" /> 
    <Style.Triggers> 
     <Trigger Property="IsSelected" Value="True"> 
      <Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" /> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

</Window.Resources> 
<ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource ContainerStyle}" /> 
+0

謝謝,請包括<列表框ItemContainerStyle =」 {StaticResource的ContainerStyle}」的ItemsSource =」 {結合邁德特}」 />在您的文章,所以人們不必在您的博客搜索。 – Shimmy 2009-09-09 02:48:39

+1

設置ListBox的ContainerStyle時遇到的一個問題是它導致與主題不兼容。我使用了你的方法,但是當我使用WPF Futures集合中的主題時,ListBoxItems具有默認樣式而不是主題樣式。就我而言,黑色背景上的黑色文字和一般的醜陋。我仍在尋找另一種方法,可能使用DataTemplate觸發器。 – 2010-02-01 03:13:14

6

還應當指出的是,StackPanel的不focuable,所以它永遠不會得到焦點(設置Focusable = True,如果你/真的/想要它聚焦)。但是,在這種情況下要記住的關鍵是TreeViewItem的StackPanel是,在這種情況下它是ItemContainer。正如Micah所建議的,調整itemcontainerstyle是一個好方法。

你也許可以做到這一點使用的DataTemplates,事情如當項目被選中或不是所有你需要做的是將使用RelativeSouce標記擴展來尋找一個ListViewItem

6

要設置的樣式datatriggers在<DataTemplate>中檢索ListBoxItem父級,並在其IsSelected更改時觸發樣式更改。例如,下面的代碼將創建一個TextBlock,其默認Foreground顏色綠色。現在,如果項目被選中,字體將變爲紅色,當鼠標懸停時,該項目將變爲黃色。這樣,您不需要按照您希望稍微更改的每個州的其他答案中的建議來指定單獨的數據模板。

<DataTemplate x:Key="SimpleDataTemplate"> 
    <TextBlock Text="{Binding}"> 
     <TextBlock.Style> 
      <Style> 
       <Setter Property="TextBlock.Foreground" Value="Green"/> 
       <Style.Triggers> 
        <DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={ 
         RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem }}}" 
           Value="True"> 
         <Setter Property="TextBlock.Foreground" Value="Red"/> 
        </DataTrigger> 
        <DataTrigger Binding="{Binding Path=IsMouseOver, RelativeSource={ 
         RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem }}}" 
           Value="True"> 
         <Setter Property="TextBlock.Foreground" Value="Yellow"/> 
        </DataTrigger> 
       </Style.Triggers> 
      </Style> 
     </TextBlock.Style> 
    </TextBlock> 
</DataTemplate> 
相關問題