Reputation: 358
I have a ComboBox in AvaloniaUI, and I want to load the list dynamically based off the names provided by an array of another class. For example, take the following code:
<ComboBox Name="Select" SelectedIndex="0"></ComboBox>
public class MainWindow : Window
{
private Note[] notes;
public MainWindow()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
notes = Utility.GetNotes();
ComboBox comboBox = this.Find<ComboBox>("Select");
foreach (Note n in notes)
{
comboBox.Items.Add(
new ComboBoxItem()
{
Content = n.Name
}
);
}
}
}
public class Note
{
public string Name;
public string NoteText;
}
I'm not sure of the proper way to do this in AvaloniaUI since in WPF you could just directly call that comboBox.Items.Add()
function. However that function doesn't seem to exist when using AvaloniaUI.
Upvotes: 4
Views: 6154
Reputation: 358
Following @kekekeks comment above I was able to make this work with a few changes:
<ComboBox Name="Select">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
public class MainWindow : Window
{
private List<Note> Notes;
public MainWindow()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
Notes = Utility.GetNotes();
ComboBox comboBox = this.Find<ComboBox>("Select");
comboBox.Items = Notes;
comboBox.SelectedIndex = 0;
}
}
public class Note
{
public string Name { get; set; }
public string NoteText { get; set; }
}
I just want to add that having the Notes variable as an array doesn't seem to work, so I had to change it to a list and I had to change the Note class to use { get; set; }
as well.
Upvotes: 3