【问题标题】:Wpf combobox with checkboxes in it带有复选框的 Wpf 组合框
【发布时间】:2013-06-15 15:51:23
【问题描述】:

我正在尝试实现一个带有复选框的组合框。我在 Google/SO 上找到的所有文章/资源都建议向我的业务对象添加一个布尔值。但我希望创建一个可重用的控件。 所以我创建了一个继承自组合框的自定义控件,并在弹出窗口中使用 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);

            }
        }

谢谢。

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:
    1. 从 ListBox 继承
    2. 在项目的模板中将CheckBox绑定到ListBoxItem.IsSelected(通过ItemContainerStyle将其设置为默认样式)。
    3. SelectionMode 设置为Multiple

    SelectedItems 然后包含您的选择。您可能还希望将您的选择区域绑定到类似SelectedItems 的逗号分隔列表(例如,可以通过转换器完成)。

    【讨论】:

    • 完美!在我的 xaml 中使用 listbox 而不是 itemscontrol 并且像魅力一样工作。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 2014-10-14
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    相关资源
    最近更新 更多