Search code examples
comboboxselecteditemavaloniaui

How to access ComboBox selected item in code behind


I would like to access the SelectedItem property for a ComboBox.

In WPF, the properties can be called by Name.Property (i.e. ComboBoxName.SelectedItem). I want to know what item is currently selected in the ComboBox, which is why I need to do this, but it is telling me the name doesn't exist in the current context. I have a SelectionChanged event handler that I want to update a string with the current selected item when it is changed.

.xaml

<ComboBox Name="Generation" Items="{Binding Generation}" SelectedIndex="0" SelectionChanged="Gen_SelectionChanged"/>

.xaml.cs

private void Gen_SelectionChanged(object sender, SelectionChangedEventArgs args)
{
   var SelectedItem = Generation.SelectedItem;
}

The error I recieve when doing this is for the Generation in Generation.SelectedItem, telling me "The name "Generation" does not exist in the current context"


Solution

  • Generated C# fields aren't supported yet. You can use this.FindControl<ComboBox>("Generation") after loading XAML instead.