简体   繁体   English

WPF组合框带有复选框

[英]Wpf combobox with checkboxes in it

I am trying to implement a combobox with checkboxes in it. 我正在尝试实现一个带有复选框的组合框。 All the articles/resources I found on Google/SO suggest adding a bool to my business object. 我在Google / SO上找到的所有文章/资源都建议在我的业务对象中添加bool。 But I am looking to create a reusable control. 但是我希望创建一个可重用的控件。 So I created a custom control inherited from combobox and changed the control in the popup with a itemscontrol. 因此,我创建了一个从combobox继承的自定义控件,并使用项目控件在弹出窗口中更改了该控件。 Here is my XAML (for brevity adding just the xaml for popup) 这是我的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>

As expected it shows a combobox with checkboxes. 如预期的那样,它显示了一个带有复选框的组合框。 But I am not able to figure out how to keep track of the checked items? 但是我不知道如何跟踪已检查的物品? I was thinking of listening to checked events but when I tried getting the Checkbox in my code-behind, FindName was returning null. 我当时想听被检查的事件,但是当我尝试在代码隐藏中获取Checkbox时,FindName返回null。

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

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

            }
        }

Thanks. 谢谢。

  1. Inherit from ListBox 从ListBox继承
  2. Bind the CheckBox to ListBoxItem.IsSelected in the template of the items (set it in default style via ItemContainerStyle ). CheckBox绑定到项目模板中的ListBoxItem.IsSelected (通过ItemContainerStyle将其设置为默认样式)。
  3. Set SelectionMode to Multiple . SelectionMode设置为Multiple

SelectedItems then contains your selection. 然后, SelectedItems包含您的选择。 You may also want to bind your selection area to something like a comma-separated list of the SelectedItems (can be done via a converter for example). 您可能还希望将选择区域绑定到诸如逗号分隔的SelectedItems列表之类的东西(例如,可以通过转换器来完成)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM