我有一个简单的ComboBox,CheckBoxes作为项目。如何防止实际选择项目。用户应该只能选中或取消选中复选框?
目前,如果我点击一个元素(不在内容或支票本身上),它就会被选中。这样做的问题是:ComboBox的TextProperty绑定到一个值,该值显示已检查项的名称。但是,如果选择了一个ComboBoxItem,则显示的文本将成为所选项目的ViewModel的值。
提前感谢任何建议。
答案 0 :(得分:2)
如果将ComboBox更改为ItemsControl怎么办:
<ItemsControl ItemsSource="{Binding Path= Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Checked}" Content="{Binding Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
使用ItemsControl而不是ComboBox将显示所有只能检查的项目。
答案 1 :(得分: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;
}
}