问题
is there any way to prevent wpf combobox from changing its text after selection changed? I have a custom control that derives from combobox and I want to be able to set the text manually after selection changed, additionally I cannot prevent the base.OnSelectionChanged from being invoked (this does the trick but it has to stay there as a part of requirements)
回答1:
In general the IsEditable
and the IsReadOnly
properties of ComboBox are used to control the level to which the display Text of the ComboBox is editable or selectable by the user.
In the msdn combobox (section remarks) you can read about it.
回答2:
I had a similar issue to solve, here's how I did it:
- My First ComboBox item is an object implementing NotifiyPropertyChanged, i can change its value at any time and it updates.
- I put its IsEnabled to False so that the user cannot select it.
If you want this item to be displayed the same way as others even when disabled, design your ItemTemplate.
- In the SelectionChanged handler, if the selected index 0, I do nothing.
- If the selectedIndex is not the first, I do my computation with this index (including updating the first item's text) then I set
SelectedIndex
to 0.
Edit 2 : try to set the grid's IsHitTestVisible to False, and to True for the CheckBoxes.
Edit 1 : If the first solution doesn't work : So the core issue is that when you click on a row and not on a CheckBox, it triggers SelectionChange. What you have to do is to handle the tunnelling left click event : Add a handler (in xaml more simple than in code) to PreviewMouseLeftButtonDown, and in the handler get the OriginalSource of the MouseButtonEventArgs. First Check that we are in second choice (index:1) of the CheckBox by checking if the Original source or one of its visual parent is the the second CheckBoxItem. If its not then return. Now if the OriginalSource is a CheckBox or is a visual parent a CheckBox then do nothing Otherwise mark the event as handled.
NB : You'll have to use VisualTreeHelper.GetParent and write a sub that checks if a Dependency object or one of its parent is of a given type. (the top most parent is the Window, having Nothing/Null as parent.) This sub will return the right typed object if found, or Noting/Null if not found.
来源:https://stackoverflow.com/questions/11429608/wpf-combobox-prevent-text-changed