I am a C++ developer and have recently started learning WPF. I am working on a wpf app where I am using MVVM. I have comboboxes and I need to add items in it. Although I generally use ComboboxPropertyName.Add(“”) to add items in it, I am looking for an efficient method which adds the items without much code length. Here is the code:
XAML:
<ComboBox Height="23" ItemsSource="{Binding BoardBoxList}" SelectedItem="{Binding SelectedBoardBoxList, Mode=TwoWay}" SelectedIndex="0" Name="comboBox2" />
ViewModel Class:
public ObservableCollection<string> BoardBoxList
{
get { return _BoardBoxList; }
set
{
_BoardBoxList = value;
OnPropertyChanged("BoardBoxList");
}
}
/// <summary>
/// _SelectedBoardBoxList
/// </summary>
private string _SelectedBoardBoxList;
public string SelectedBoardBoxList
{
get { return _SelectedBoardBoxList; }
set
{
_SelectedBoardBoxList = value;
OnPropertyChanged("SelectedBoardBoxList");
}
}
Here Is how I had added items in my combobox in C++:
static const signed char boards[][9] = {
{}, // left blank to indicate no selection
{ 'S', '1', '0', '1', '0', '0', '1', '2', 0 }, // redhook
{ 'S', '1', '0', '1', '0', '0', '1', '8', 0 }, // bavaria
{ 'S', '1', '0', '1', '0', '0', '2', '0', 0 }, // flying dog
};
m_boardBox = new ComboBox(String::empty);
for(int i = 1; i < 4; i++)
m_boardBox->addItem(String((char*)(boards[i])), i);
m_boardBox->setSelectedId(2); // select Bavaria by default
addAndMakeVisible(m_boardBox);
If you notice above, you will find the loop adding items easily. This is how i wanna add items to my combobox.
If I use _BoardBoxList.Add("...."); I will have to use many .Adds. Is their an efficient way where I can store the items in a list/collection and add them into the combobox in the form of for loop just like above?
Please help 🙂
You can use a constructor of ObservableCollection that can consume an enumerable as a start set.
Boards would have to be an collection of strings not chars.
Edit: