2012-02-21 136 views
0

我搜索了這個主題並找到了幾個討論。 我不喜歡那些實現是他們要麼隱含特殊的綁定數據(與IsSelected屬性)或缺乏正常的鍵盤支持。選擇/取消選中XAML中「CheckListBox」中的所有複選框

列表中的複選框更多的是裝飾性的東西,而不是功能性的擴展,因此應該對其進行相應的處理。

我從這個好的和有用的文章開始:http://www.gbogea.com/2010/01/02/mvvm-multiselect-listbox

但我beleive贊成視圖模型的黑客查看不太好做法。它的ViewModel適用於視圖和模型。當然,恕我直言。

因此,我改變一點點,這個XAML完成:

<ListBox Name="checkboxList" 
       ItemsSource="{Binding Sports}" 
       Margin="0,5" 
       SelectionMode="Multiple"> 
      <ListBox.ItemContainerStyle> 
       <Style> 
        <Setter Property="ListBoxItem.Background" Value="Transparent"/> 
        <Setter Property="ListBoxItem.Template"> 
         <Setter.Value> 
          <ControlTemplate TargetType="{x:Type ListBoxItem}"> 
           <Border x:Name="Bd" 
           SnapsToDevicePixels="true" 
           Background="{TemplateBinding Background}" 
           BorderBrush="{TemplateBinding BorderBrush}" 
           BorderThickness="{TemplateBinding BorderThickness}" 
           Padding="{TemplateBinding Padding}"> 
            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
               VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
               SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> 
           </Border> 
          </ControlTemplate> 
         </Setter.Value> 
        </Setter> 
       </Style> 
      </ListBox.ItemContainerStyle> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <CheckBox IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}, Path=IsSelected, Mode=TwoWay}" 
           Content="{Binding}"/> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

這裏選中複選框處於同步與ListBoxItem.IsSelected和列表框不知道綁定數據特殊性。

這是好的。 但是有什麼辦法通過添加一個複選框到控件模板來爲ListBox添加Select | Deselect All?僅使用XAML。

+0

問題是? – vulkanino 2012-02-21 14:06:56

+0

呃..忘了問題=)對不起。 – 2012-02-21 14:13:40

回答

1

你可以使用例如InteractivityBlend SDK

<ListBox ItemsSource="{Binding Data}" SelectionMode="Extended"> 
    <ListBox.Template> 
     <ControlTemplate TargetType="ListBox"> 
      <StackPanel> 
       <CheckBox Content="All"> 
        <i:Interaction.Triggers> 
         <i:EventTrigger EventName="Checked"> 
          <is:CallMethodAction MethodName="SelectAll" 
            TargetObject="{Binding RelativeSource={RelativeSource TemplatedParent}}" /> 
         </i:EventTrigger> 
         <i:EventTrigger EventName="Unchecked"> 
          <is:CallMethodAction MethodName="UnselectAll" 
            TargetObject="{Binding RelativeSource={RelativeSource TemplatedParent}}" /> 
         </i:EventTrigger> 
        </i:Interaction.Triggers> 
       </CheckBox> 
       <ItemsPresenter /> 
      </StackPanel> 
     </ControlTemplate> 
    </ListBox.Template> 
</ListBox> 

做這樣的事情不過,這並沒有解決一個問題,你沒有提到或想到的,即該CheckBox的狀態時不會改變選擇被改變而不使用它。您可以使用MultiBinding和值轉換器將IsChecked狀態綁定到正確的狀態,然後您也可以刪除事件。這也是相當混亂。