wpf combobox with checkbox - selecteditem

前端 未结 2 1466
忘掉有多难
忘掉有多难 2021-01-06 23:28

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?

相关标签:
2条回答
  • 2021-01-06 23:56

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-07 00:14

    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.

    0 讨论(0)
提交回复
热议问题