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