2010-08-29 93 views
4

我有一個風格的列表框。當懸停和選中時,列表框項目會改變顏色。懸停並選擇正常工作。但是,當選擇一個項目時,將鼠標從其上移開並將其懸停在其上,使其回到懸停/未選中狀態,即使它仍處於選中狀態。如何將listboxitem保持在「選定」的可視狀態?自定義樣式的列表框 - 我如何保留選定項目的樣式?

<Style x:Name="myListBoxItemStyle" TargetType="ListBoxItem"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="ListBoxItem"> 
       <Border x:Name="myBorder" CornerRadius="5" BorderThickness="3" Background="#FF292121" Margin="0"> 
        <Grid HorizontalAlignment="Stretch"> 
         <ContentPresenter Content="{TemplateBinding Content}" Margin="5,0,5,0" /> 
        </Grid> 
        <VisualStateManager.VisualStateGroups> 
         <VisualStateGroup x:Name="CommonStates"> 
          <VisualState x:Name="Normal"/> 
          <VisualState x:Name="MouseOver"> 
           <Storyboard> 
            <ColorAnimation Storyboard.TargetName="myBorder" Storyboard.TargetProperty="(Background).(SolidBrush.Color)" Duration="00:00:00.2" To="#FF949290" /> 
           </Storyboard> 
          </VisualState> 
          <VisualState x:Name="Disabled"/> 
         </VisualStateGroup> 
         <VisualStateGroup x:Name="SelectionStates"> 
          <VisualState x:Name="Unselected" /> 
          <VisualState x:Name="Selected"> 
           <Storyboard> 
            <ColorAnimation Storyboard.TargetName="myBorder" Storyboard.TargetProperty="(Background).(SolidBrush.Color)" Duration="00:00:00.2" To="#FF949290" /> 
           </Storyboard> 
          </VisualState> 
          <VisualState x:Name="SelectedUnfocused"/> 
         </VisualStateGroup> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

<Style x:Key="myListBoxStyle" TargetType="ListBox"> 
    <Setter Property="Background" Value="Transparent"/> 
    <Setter Property="Margin" Value="0"/> 
    <Setter Property="BorderThickness" Value="0"/> 
    <Setter Property="ItemContainerStyle" Value="{StaticResource myListBoxItemStyle}"/> 
    <Setter Property="VerticalAlignment" Value="Bottom"/> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="ListBox"> 
       <Grid Margin="0"> 
        <ItemsPresenter /> 
       </Grid> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
    <Setter Property="ItemsPanel"> 
     <Setter.Value> 
      <ItemsPanelTemplate> 
       <StackPanel Orientation="Horizontal"/> 
      </ItemsPanelTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

<ListBox Name="theControl" Style="{StaticResource myListBoxStyle}" /> 

回答

8

什麼事情發生是你的狀態(選擇mousover)從不同的狀態組爭奪同一個屬性(myBorders的背景)。您將不得不添加另一個元素(可能是矩形),並在其中一個狀態中更改該元素的背景。

一般而言,您不應該從不同狀態組中的狀態操縱相同元素的相同屬性。視覺狀態管理器不知道如何處理這種情況,因爲它不知道哪個狀態應該優先。

+1

謝謝。應該有這個想法。 對於遇到類似問題的其他人,我在第一個邊框內添加了另一個邊框,它們具有相同的形狀,並從Transparent動畫到選定時的顏色。現在完美工作。 – Adam 2010-08-29 21:45:11

+0

真的很酷的解決方案!謝謝.. – 2011-11-04 13:31:10

相關問題