Search code examples
c#xamluwpcombobox

UWP Combobox behaviour: save user input when dropdown opened


I am making an app using UWP, xaml, c#

I have a combobox with a list of premade values: 1, 2, 3, 4, 5. I made the combobox editable as I want the user to be able to enter any value.

If the user clicks the textbox and enters a value, then clicks anywhere outside of the control, the entered value is displayed in the textbox and control disengaged. Just as I would expect and like.

However if the user opens the dropdown list and writes a value in the textbox, then clicks outside of the control to close it, the entered value is not saved but reverted to the previous value. In order to save the value, the user have to click a second time on the dropdown button to close the dropdown and save the user entered value, or press enter to save it before clicking outside.

To me this is not intuitive behaviour and requires extra input from the user, and I dont understand why there is this difference in behaviour when the dropdown is opened or closed?

Is there anyway to make the user entered values be saved when clicking outside the control if the dropdown has been opened?

Hope this question made sense.


Solution

  • Here is a workaround, you can save the value of the textbox before the drop-down box is closed and set it after drop-down box is closed. It use three events LosingFocus,SelectionChanged and DropDownClosed.

    <ComboBox x:Name="ComboTest" Height="80" Width="296" ItemsSource="{x:Bind items}" 
                      IsEditable="True" LosingFocus="ComboTest_LosingFocus" SelectionChanged="ComboTest_SelectionChanged" DropDownClosed="ComboTest_DropDownClosed"/>
    

    public sealed partial class MainPage : Page
    {
        ObservableCollection<string> items = new ObservableCollection<string>();
    
        private string comboText = "";
        public MainPage()
        {
            this.InitializeComponent();
    
            items.Add("A");
            items.Add("B");
            items.Add("C");
            items.Add("D");
        }
    
        private void ComboTest_LosingFocus(UIElement sender, LosingFocusEventArgs args)
        {
            ComboBox comboBox = sender as ComboBox;
            comboText = comboBox.Text;
        }
    
        private void ComboTest_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            comboText = comboBox.SelectedValue.ToString();
        }
    
        private void ComboTest_DropDownClosed(object sender, object e)
        {
            ComboBox comboBox = sender as ComboBox;
            comboBox.Text = comboText;
        }
    }