2013-06-19 202 views
0

我正在嘗試使用其中的複選框實現組合框。我在Google/SO上找到的所有文章/資源都建議添加一個bool到我的業務對象。但我期待創建一個可重用的控件。 所以我創建了一個從組合框繼承的自定義控件,並使用itemcontrol改變了彈出框中的控件。 這是我的XAML(爲簡便起見將剛剛的XAML彈出)帶有複選框的Wpf組合框

<Popup Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True" Focusable="False" PopupAnimation="Slide"> 
<Grid Name="DropDown" SnapsToDevicePixels="True" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}"> 
    <Border x:Name="DropDownBorder" Background="{StaticResource BackgroundBrush}" BorderThickness="1" BorderBrush="{StaticResource BorderBrush}" /> 
    <ScrollViewer Margin="4,6,4,6" SnapsToDevicePixels="True"> 
     <ItemsControl ItemsSource="{Binding ItemsSource,RelativeSource={RelativeSource AncestorType=local:CheckedComboBox}}"> 
      <ItemsControl.ItemTemplate> 
          <DataTemplate> 
           <CheckBox Content="{Binding}" x:Name="PART_Checkbox" /> 
          </DataTemplate> 
       </ItemsControl.ItemTemplate> 
      </ItemsControl> 
    </ScrollViewer> 
    </Grid> 
</Popup> 

正如預期的那樣它顯示了複選框的組合框。但我無法弄清楚如何跟蹤檢查項目? 我正在考慮收聽選中的事件,但是當我嘗試在代碼隱藏中獲取複選框時,FindName返回null。

public override void OnApplyTemplate() 
     { 
      base.OnApplyTemplate(); 

      if (this.Template != null) 
      { 
       var v = Template.FindName("PART_Checkbox",this); 
       Debug.Assert(v != null); 

      } 
     } 

謝謝。

回答

1
  1. 繼承從Control
  2. 綁定中的項目(通過ItemContainerStyle將其設置爲默認樣式)的模板CheckBoxListBoxItem.IsSelected
  3. SelectionMode設置爲Multiple

SelectedItems然後包含您的選擇。您可能還想將選擇區域綁定到類似於逗號分隔列表SelectedItems(可通過轉換器完成)的東西。

+0

完美!在我的xaml中使用listbox而不是itemscontrol,並像魅力一樣工作。謝謝 –