2

I have a simple ComboBox with CheckBoxes as Items. How can I prevent the actual selection of the items. The user should only be able to check or uncheck the checkboxes?

Currently if I click on an element (not on the content or the check itself) it becomes selected. The problem with this is: The TextProperty of the ComboBox is bound to a value which displays the names of the checked items. But if one ComboBoxItem becomes selected the displayed text becomes the value of the ViewModel of the selected item.

Thanks in advance for any suggestion.

Daniel Bişar
  • 2,663
  • 7
  • 32
  • 54

2 Answers2

2

What about if you change your ComboBox to ItemsControl:

<ItemsControl ItemsSource="{Binding Path= Items}">
  <ItemsControl.ItemTemplate>  
    <DataTemplate>  
      <CheckBox IsChecked="{Binding Checked}" Content="{Binding Name}" />
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl> 

Having an ItemsControl instead of a ComboBox will display all the items only checkable.

WaltiD
  • 1,932
  • 2
  • 23
  • 25
  • The reason i use the combobox is that i haven't so much place in this area where i am using it. If i would use an itemcontrol i would not have the ability to "popup" the checkboxes. To use an Expander is also not satisfying. – Daniel Bişar Jun 28 '11 at 08:34
  • So you could change the apperance of the selection style. Check [this question](http://stackoverflow.com/questions/3829315/stop-highlighting-selected-item-wpf-combobox) – WaltiD Jun 28 '11 at 10:53
1

Ok, I already tried before to use GetBindingExpression(...).UpdateTarget() because my TextProperty is bound but nothing happend. This function will only have an effect after the layout was updated. So the result:

/// <summary>
/// Prevents the selection of an item and displays the result of the TextProperty-Binding
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SeveritiesComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox box = sender as ComboBox;

    if (box == null)
        return;

    if (box.SelectedItem != null)
    {
        box.SelectedItem = null;

        EventHandler layoutUpdated = null;

        layoutUpdated = new EventHandler((o, ev) =>
        {
            box.GetBindingExpression(ComboBox.TextProperty).UpdateTarget();
            box.LayoutUpdated -= layoutUpdated;
        });

        box.LayoutUpdated += layoutUpdated;
    }
}
Daniel Bişar
  • 2,663
  • 7
  • 32
  • 54