2010-11-14 36 views
0

我有一個應用自定義樣式的ListBox。看來有時候,當我選擇一種顏色,然後另一個(不按Ctrl/Shift鍵),它看起來像2項被選中,有時甚至更WPF:多於一個項目呈現爲列表框中的選定內容?

alt text

與此渲染請告訴我?我的XAML看起來像

<ListBox ItemsSource="{Binding ThemeColors}" SelectedValue="{Binding Color}" SelectionChanged="ListBox_SelectionChanged" ScrollViewer.HorizontalScrollBarVisibility="Disabled"> 
    <ListBox.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapPanel Margin="3" /> 
     </ItemsPanelTemplate> 
    </ListBox.ItemsPanel> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Setter Property="Padding" Value="0" /> 
      <Setter Property="Template"> 
       <Setter.Value> 
        <ControlTemplate TargetType="{x:Type ListBoxItem}"> 
         <Border x:Name="Bd" SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1" Padding="1"> 
          <Rectangle Width="20" Height="20"> 
           <Rectangle.Fill> 
            <SolidColorBrush Color="{Binding}" /> 
           </Rectangle.Fill> 
          </Rectangle> 
         </Border> 
         <ControlTemplate.Triggers> 
          <Trigger Property="IsSelected" Value="true"> 
           <Setter Property="BorderBrush" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/> 
          </Trigger> 
          <MultiTrigger> 
           <MultiTrigger.Conditions> 
            <Condition Property="IsSelected" Value="true"/> 
            <Condition Property="Selector.IsSelectionActive" Value="false"/> 
           </MultiTrigger.Conditions> 
           <Setter Property="BorderBrush" TargetName="Bd" Value="#FF999999"/> 
          </MultiTrigger> 
         </ControlTemplate.Triggers> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 

更新:11月14日

所以我也跟着@Meleak意見和刪除所有重複,也恰巧是一些。但現在有另一個問題。有時,當我選擇一種顏色時,邊框不顯示,IsSelected樣式不活動?但預覽顏色更新,顯示綁定工作。

http://screenr.com/18c

+0

每次都會發生這些特殊顏色嗎?你可以將你的代碼放在/查看模型嗎? – 2010-11-14 09:55:52

+0

是的這個應用程序背後的代碼實際上是視圖模型... http://pastebin.com/p5McmADR – 2010-11-14 13:31:53

回答

1

我覺得你有完全相同的問題,因爲Gishu在this問題。基本上,Color是一個結構體,而不是一個Class,當你選擇一個在你的ListBox中多次表示的Color時,選擇將失敗,因爲它無法區分兩者之間的區別。例如,等於成立。

Color color1 = Colors.AliceBlue; //#FFF0F8FF 
Color color2 = Color.FromArgb(255, 240, 248, 255); //#FFF0F8FF 
bool equal = (color1 == color2); 

我可以爲你的問題想出三種解決方案。

  1. 從ThemeColors刪除重複
  2. 改變集合到的SolidColorBrush(這是一類,而不是一個結構)和綁定到顏色。
  3. 創建自己的Color類,例如MyColor。
+1

這也是我同樣的問題的經驗。我會爲#3投票,並且不要重寫equals,這樣listbox將使用引用相等,這就是你想要的 – 2010-11-14 11:45:57

+0

這很有效,但現在,我注意到有時當我選擇一種顏色時, IsSelected風格不顯示。請參閱「更新:11月14日」 – 2010-11-14 14:08:38

+0

我無法重現您的問題。我使用了你發佈的ListBox,當我刪除所有重複項時,一切正常。我建議你嘗試其他兩個選項之一,因爲它們沒有結構問題。 – 2010-11-14 14:31:53

相關問題