2011-06-28 606 views
2

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

当前,如果我点击某个元素(而不是内容或检查本身),它会变成被选中的。与此问题是:ComboBox的TextProperty绑定到一个值显示检查项目的名称。但是,如果选择了一个ComboBoxItem,则显示的文本将变为所选项目的ViewModel的值。

先感谢您的任何建议。

回答

1

好吧,我已经尝试过使用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; 
    } 
} 
2

样,如果你改变你的组合框的ItemsControl什么:

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

有一个ItemsControl,而不是一个组合框将显示所有项目只可检查的。

+0

我用的是组合框的原因是,我有这方面我在哪里使用它没有那么多的地方。如果我使用itemcontrol,我将无法“弹出”复选框。使用扩展器也不令人满意。 – SACO

+0

所以你可以改变选择风格的外观。检查[这个问题](http://stackoverflow.com/questions/3829315/stop-highlighting-selected-item-wpf-combobox) – WaltiD

+0

谢谢你的回答。我找到了另一个解决方案 – SACO