[WPF] Checkboxes in ComboBox - display number of checked items when closed
Hi,
I need to have a ComboBox that displays a list of CheckBoxes when dropped down so the user can check the relevant ones and then close it again. When closed, I want the ComboBox (the 'Text' area) to display the number of checked items (for example "Checked items: 3").
I cannot seem to figure this out... I can get the CheckBoxes in the ComboBox, that's easy enough using a DataTemplate, but then it also uses the same template for the 'selected item' and thus shows the last clicked ("selected") CheckBox in the text area. Selecting an item is actually not really defined for this ComboBox, I just need the user to check some items and be done with it, he doesn't need to select any items.
I've tried looking for solutions, and there seem to be a few different solutions to having a different template for the selected item as for the dropdown items, but none seem to work for me...
The code-behind for all of my attempts is:
vb.net Code:
Imports System.Collections.ObjectModel
Class MainWindow
Private items As ObservableCollection(Of ComboBoxItem)
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
items = New ObservableCollection(Of ComboBoxItem)
For i As Integer = 1 To 5
items.Add(New ComboBoxItem() With {.Text = "Item " & i})
Next
comboBox.ItemsSource = items
End Sub
Private ReadOnly Property CheckedItems As Integer
Get
Return items.Where(Function(cbi) cbi.IsChecked).Count()
End Get
End Property
End Class
Public Class ComboBoxItem
Private _Text As String
Public Property Text() As String
Get
Return _Text
End Get
Set(ByVal value As String)
_Text = value
End Set
End Property
Private _IsChecked As Boolean
Public Property IsChecked() As Boolean
Get
Return _IsChecked
End Get
Set(ByVal value As Boolean)
_IsChecked = value
End Set
End Property
End Class
Attempt 1:
Source
My XAML code:
Code:
<Window.Resources>
<ControlTemplate x:Key="X" TargetType="{x:Type ContentControl}">
<CheckBox Content="{Binding Text}" IsChecked="{Binding IsChecked}" />
</ControlTemplate>
</Window.Resources>
<Grid>
<ComboBox Name="comboBox" VerticalAlignment="Top" Margin="10">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=CheckedItems}" />
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Margin" Value="5"/>
<Setter Property="Template" Value="{StaticResource X}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
</Grid>
I am trying to bind the TextBlock Text property to the 'CheckedItems' property in my Window, I hope I'm not screwing that up...
Anyway, the result is a dropdown containing CheckBox items which I can check (correct), but after closing, the 'text area' remains empty. Even if I select an item (which isn't really defined for me) it displays nothing.
(Text too long, see post 2...)
Re: [WPF] Checkboxes in ComboBox - display number of checked items when closed
Attempt 2:
Source
My XAML:
Code:
<Window.Resources>
<DataTemplate x:Key="ComplexTemplate">
<CheckBox Content="{Binding Text}" IsChecked="{Binding IsChecked}" />
</DataTemplate>
<ControlTemplate x:Key="SimpleTemplate">
<TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=CheckedItems}" />
</ControlTemplate>
</Window.Resources>
<Grid>
<ComboBox Name="comboBox" VerticalAlignment="Top" Margin="10">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<ContentControl x:Name="content" Content="{Binding}" ContentTemplate="{StaticResource ComplexTemplate}"/>
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ComboBoxItem}}" Value="{x:Null}">
<Setter TargetName="content" Property="ContentTemplate" Value="{StaticResource SimpleTemplate}"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
This produces an error as soon as I start, saying it cannot convert a ControlTemplate to a DataTemplate...
Attempt 3:
Finally I simply tried to bind the Text property of the ComboBox to the property in my Window (same as before), but nothing... The text area stays empty.
I'm kinda out of ideas... What else can I do? This can't be so hard?
Re: [WPF] Checkboxes in ComboBox - display number of checked items when closed
Sounds to me like you don't actually want a ComboBox, but rather an Expander. What you're describing is really strange behaviour for a ComboBox. The Expander control will give you that "hiding" behaviour that you're after, without the strangeness of the ComboBox implementation.
Re: [WPF] Checkboxes in ComboBox - display number of checked items when closed
To fix your issue with the Count of items.
First off, I took your code and removed the code behind into its own class, MainWindowViewModel.
In the constructor of the Window, I instantiated one of them and set it as the DataContext of the Window:
vbnet Code:
Class MainWindow
Public Sub New()
' This call is required by the designer.
InitializeComponent()
Me.DataContext = New MainWindowViewModel()
End Sub
End Class
Normally, you'd set the DataContext from outside the Window, but this'll do for now.
Now, our XAML looks a bit like this:
Code:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Expander>
<ListView ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Text}" IsChecked="{Binding IsChecked}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Expander>
<TextBlock Text="{Binding CheckedCount}" />
</StackPanel>
</Window>
(I've changed some of the property names slightly)
Now, the problem with the Binding for CheckedCount is that it needs to know when the CheckedCount property changes. Which it can't at the moment. So, get that ViewModel class implementing INotifyPropertyChanged so it can raise the PropertyChanged event when the items are checked on/off. But we don't yet know that so let's add an event to the ComboBoxItem class that lets us know when it gets checked:
vbnet Code:
Public Class ComboBoxItem
' ...
Private _IsChecked As Boolean
Public Property IsChecked() As Boolean
Get
Return _IsChecked
End Get
Set(ByVal value As Boolean)
_IsChecked = value
RaiseEvent IsCheckedChanged(Me, EventArgs.Empty)
End Set
End Property
Public Event IsCheckedChanged(sender As Object, eventArgs As EventArgs)
End Class
That lets us hook on to the event, and raise our own event in the ViewModel:
vbnet Code:
Imports System.Collections.ObjectModel
Imports System.ComponentModel
Public Class MainWindowViewModel
Implements INotifyPropertyChanged
Private m_items As ObservableCollection(Of ComboBoxItem)
Public Sub New()
m_items = New ObservableCollection(Of ComboBoxItem)
For i As Integer = 1 To 5
Dim comboBoxItem As New ComboBoxItem() With {.Text = "Item " & i}
AddHandler comboBoxItem.IsCheckedChanged, AddressOf Me.ComboBoxItemIsCheckedChanged
m_items.Add(comboBoxItem)
Next
End Sub
Public ReadOnly Property Items As ObservableCollection(Of ComboBoxItem)
Get
Return m_items
End Get
End Property
Public ReadOnly Property CheckedCount As Integer
Get
Return m_items.Where(Function(cbi) cbi.IsChecked).Count()
End Get
End Property
Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
Private Sub ComboBoxItemIsCheckedChanged(ByVal sender As Object, ByVal eventArgs As EventArgs)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("CheckedCount"))
End Sub
End Class