2011-07-08 57 views
4

我有一個WPF Window,它基本上有一個ListBox,它顯示項目列表。當列表失去焦點時,WPF SelectedItem顏色消失

然後我有一個ListView基本上顯示ListBoxSelectedItem的細節。

事情是,當焦點不再在ListBox上時,突出顯示的顏色消失,我看不到哪個主項目被選中了。

你知道我該如何解決這個問題嗎?

回答

6

的最快方法是使用一種風格的一個ListBoxItem覆蓋默認的系統顏色(即確保該項目保持突出顯示。):

<Style TargetType="ListBoxItem"> 
    <Style.Resources> 
     <!--SelectedItem with focus--> 
     <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
     Color="LightBlue" Opacity=".4"/> 
     <!--SelectedItem without focus--> 
     <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" 
     Color="LightBlue" Opacity=".4"/> 
    </Style.Resources> 
</Style> 

這是怎麼樣的一個用於爲列表項定義ItemTemplate的稍微複雜(但更容易控制)的方法的捷徑。網上有很多例子,所以我不會在這裏提到。

+0

兩個答案都以相同的解決方案結束,但我選擇了這個答案,因爲答案包含在帖子中。 – SRKX

0
<Style> 
    <Style.Triggers> 
     <DataTrigger Binding="{Binding RelativeSource= 
         {RelativeSource Mode=FindAncestor, 
         AncestorType={x:Type ListBoxItem}}, 
         Path=IsSelected}" 
     Value="True"> 
     <Setter Property="Panel.Background" Value="Red" /> 
     </DataTrigger> 
    </Style.Triggers> 
</Style> 
0

這個問題也可以通過數據綁定來解決。 如果ListView/ListBox SelectedItem綁定到實現INotifyPropertyChanged並且綁定模式爲「TwoWay」的ViewModel中的屬性,那麼當ListView/ListBox再次獲得焦點時,數據綁定將自動選擇先前選擇的項目。