【问题标题】:wpf combobox with checkbox - selecteditem带有复选框的wpf组合框 - selecteditem
【发布时间】:2011-09-24 02:03:40
【问题描述】:

我有一个简单的组合框,其中复选框作为项目。如何防止项目的实际选择。用户应该只能选中或取消选中复选框?

目前,如果我单击一个元素(不是内容或检查本身),它就会被选中。这样做的问题是:ComboBox 的 TextProperty 绑定到一个显示选中项名称的值。但是,如果一个 ComboBoxItem 被选中,则显示的文本将成为所选项目的 ViewModel 的值。

提前感谢您的任何建议。

【问题讨论】:

    标签: wpf combobox checkbox selecteditem


    【解决方案1】:

    如果将 ComboBox 更改为 ItemsControl 会怎样:

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

    使用 ItemsControl 而不是 ComboBox 将显示所有仅可检查的项目。

    【讨论】:

    • 我使用组合框的原因是我在这个区域没有太多地方使用它。如果我使用 itemcontrol,我将无法“弹出”复选框。使用 Expander 也不令人满意。
    • 所以你可以改变选择样式的外观。检查this question
    【解决方案2】:

    好的,我之前已经尝试过使用 GetBindingExpression(...).UpdateTarget(),因为我的 TextProperty 已绑定但没有发生任何事情。此功能只有在布局更新后才会生效。所以结果:

    /// <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;
        }
    }
    

    【讨论】: