Reputation: 138
I have a non-editable combobox (SupplierDropdown
), and I would like when the user chooses the last value on the list, the combobox should become editable, with no value and automatically focused ready for the user to type their value. In other words, an editable, blank box with a blinking cursor ready for input.
Here's the code I have:
private void SupplierDropdown_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (SupplierDropdown.SelectedIndex == SupplierDropdown.Items.Count - 1)
{
SupplierDropdown.IsEditable = true;
SupplierDropdown.Text = "";
SupplierDropdown.Focus();
}
}
However, although the combobox indeed becomes editable, the rest of the code doesn't seem to work: (a) the combobox doesn't clear the value the user chose, and (b) the combobox doesn't get the focus, the user needs to hit tab once to see the blinking cursor in the combobox.
How can I make this work?
Upvotes: 0
Views: 695
Reputation: 185350
This seems like a major pain, because the control just is not intended to be used that way. Even if you get the initial logic to work, it is difficult to turn the editable flag back off in a sound way. When the user enters text that partially matches a given option it will select said option. How do you know whether that selection was caused by accident or intentionally and thus whether the editable flag should be set to false again?
Would recommend the additional TextBox
scheme, where you just show a TextBox
for any custom values, can be done in XAML only (if you know what value to trigger on) but that's not necessary.
<ComboBox Name="cb" SelectedValuePath="Content">
<ComboBoxItem>A</ComboBoxItem>
<ComboBoxItem>B</ComboBoxItem>
<ComboBoxItem>Other</ComboBoxItem>
</ComboBox>
<TextBox>
<TextBox.Style>
<Style TargetType="TextBox">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedValue, ElementName=cb}" Value="Other">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
(PS: This is an example of using the item/value instead of the index, even if someone decides that the "other" option should be at the top instead, the code will still work as intended, yours would not.)
Upvotes: 1