WPF - auto-update content

I have an example mvvm application. The user interface has a text box, button, and combo box. when I enter something into the text box and press the button, the text that I entered is added to the observed collections. Combobox is attached to this collection. How to get combobox to automatically display a newly added row?

+6
c # wpf mvvm combobox auto-update
source share
2 answers

As I understand it correctly, you want to add an item and select it. Here is an example of how this 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)); } } } 

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

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

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

Thus, you must explicitly indicate the added item selected after adding it to the collection.

Because the OnItemsChanged method of the ComboBox class is protected and cannot be used.

+5
source share

If the ComboBox is bound to an ObservableCollection, the ComboBox will be updated immediately after the collection is changed.

This is the advantage of using an ObservableCollection - you do not need to do any extra coding to update the user interface.

If this is not the behavior you are seeing, perhaps you can publish the / xaml code.

+3
source share

All Articles