Wpf组合框,里面有复选框

时间:2013-06-19 07:49:40

标签: c# wpf xaml

我正在尝试使用复选框来实现一个组合框。我在Google / SO上找到的所有文章/资源都建议在我的业务对象中添加一个bool。但我希望创建一个可重用的控件。 所以我创建了一个继承自combobox的自定义控件,并使用itemscontrol更改了弹出窗口中的控件。 这是我的XAML(为简洁起见,仅为弹出式添加xaml)

<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>

正如预期的那样,它显示了一个带复选框的组合框。但我无法弄清楚如何跟踪检查项目?  我正在考虑收听已检查的事件,但当我尝试在我的代码隐藏中获取Checkbox时,FindName返回null。

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

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

            }
        }

感谢。

1 个答案:

答案 0 :(得分:1)

  1. 从ListBox继承
  2. CheckBox绑定到项目模板中的ListBoxItem.IsSelected(通过ItemContainerStyle将其设置为默认样式。)
  3. SelectionMode设为Multiple
  4. SelectedItems然后包含您的选择。您可能还希望将选择区域绑定到类似逗号分隔的SelectedItems列表(例如,可以通过转换器完成)。