I have a ComboBox cbo1
.
I'm trying to change the item source using the ViewModel
with CollectionChanged
but the ComboBox items stay blank and won't update.
I've tried several examples and solutions here, but don't know how to implement them right.
XAML
<ComboBox x:Name="cbo1"
ItemsSource="{Binding cbo1_Items, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding cbo1_SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left"
Margin="0,0,0,0"
VerticalAlignment="Top"
Width="105"
Height="22" />
ViewModelBase Class
Bind ComboBox Items
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string propName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
public ViewModelBase()
{
_cbo1_Items = new ObservableCollection<string>();
_cbo1_Items.CollectionChanged += cbo1_Items_CollectionChanged;
}
// Notify Collection Changed
//
public void cbo1_Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Notify("cbo1_Items");
}
// Item Source
//
public static ObservableCollection<string> _cbo1_Items = new ObservableCollection<string>();
public static ObservableCollection<string> cbo1_Items
{
get { return _cbo1_Items; }
set { _cbo1_Items = value; }
}
// Selected Item
//
public static string cbo1_SelectedItem { get; set; }
}
Example Class
In this class I want to change the ComboBox Item Source.
// Change ViewModel Item Source
//
ViewModelBase._cbo1_Items = new ObservableCollection<string>()
{
"Item 1",
"Item 2",
"Item 3"
};
// ...
// Change Item Source Again
//
ViewModelBase._cbo1_Items = new ObservableCollection<string>()
{
"Item 4",
"Item 5",
"Item 6"
};