WPF - Auto refresh combobox content

后端 未结 2 877
旧时难觅i
旧时难觅i 2021-01-05 11:25

I got a sample mvvm app. The UI has a textbox, a button and a combobox. when I enter something in the textbox and hit the button, the text I enter gets added to an observabl

相关标签:
2条回答
  • 2021-01-05 11:49

    If the ComboBox is bound to an ObservableCollection, the ComboBox will be updated as soon as the collection is changed.

    That's the advantage of using an ObservableCollection - you don't need to do any extra coding to update the UI.

    If this is not the behavior you're seeing, perhaps you can post some code/xaml.

    0 讨论(0)
  • 2021-01-05 11:53

    As I understand correctly, you want to add an item and select it. Here is the example how it can be done using ViewModel and bindings.

    Xaml:

    <StackPanel>
        <TextBox Text="{Binding ItemToAdd}"/>
        <ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />
        <Button Content="Add" Click="Button_Click"/>
    </StackPanel>
    

    ViewModel:

    public class MainViewModel:INotifyPropertyChanged
    {
        public ObservableCollection<string> Items { get; set; }
    
        public string ItemToAdd { get; set; }
    
        private string selectedItem;
    
        public string SelectedItem
        {
            get { return selectedItem; }
            set
            {
                selectedItem = value;
                OnPropertyChanged("SelectedItem");
            }
        }
    
        public void AddNewItem()
        {
            this.Items.Add(this.ItemToAdd);
            this.SelectedItem = this.ItemToAdd;
        }
    
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    The MainViewModel has 3 properties (one for the TextBox and two other for the ComboBox) and the method AddNewItem without parameters.

    The method can be triggered from a command, but there is no standard class for commands, so I will call it from the code-behind:

       ((MainViewModel)this.DataContext).AddNewItem();
    

    So you must explicitly set an added item as selected after you add it to a collection.

    Because the method OnItemsChanged of the ComboBox class is protected and can't be used.

    0 讨论(0)
提交回复
热议问题