Home > Software engineering >  Binding a SelectedItem in WPF Combobox to property
Binding a SelectedItem in WPF Combobox to property

Time:12-21

I am trying to bind a property to a combobox in WPF so that when I select one of the items of the combobox, the SelectedValue of my combobox is stored to a property called eventNumber, which is just a number. I am not sure why it is not working. At the moment I am importing the values of a SQL table with events, with two fields, Name and eventNumber. I call this table using Rest Sharp as shown in code behind and deserialize the json as a list, whose elemnts are then passed with a foreach loop to a System.Collections.ObjectModel.ObservableCollection for binding. This works fine and my ComboBox displays the name of the events when selected. However, I would like to bind the SelectedItem of my combobox to the eventNumber of the Collection, and I am not very sure how.

XAML Code:

<Grid>
    <StackPanel>
            <ComboBox x:Name="ComboEvents" IsEditable="False" Height="20" Width="500" Margin="30,0,0,0" ItemsSource="{Binding listEvents}" SelectedItem="eventNumber" DisplayMemberPath="Name"/>
    </StackPanel>
</Grid>

C# Code:

public partial class MainWindow : Window
{
    public System.Collections.ObjectModel.ObservableCollection<Events> listEvents { get; }
    public MainWindow()
    {
        InitializeComponent();

        //calls the names of the events
        var client1 = new RestClient("http://ip port");
        var request1 = new RestRequest("myMethod that gets all the events from a sql table", Method.Get);
        var Response1 = client1.Execute(request1);
        
        if (Response1.StatusCode == System.Net.HttpStatusCode.OK)
        {
            var listEvents = JsonConvert.DeserializeObject<List<Events>>(Response1.Content);
            listEvents = new System.Collections.ObjectModel.ObservableCollection<Event>();
            foreach (Event event in listEvents)
            {
                listEvents.Add(new Events { Name = event.Name, eventNumber= event.eventNumber}); //adds each event to listEvents collection
            }
        }

        DataContext = this;
    }
    

    public class Event
    {
        public string eventNumber{ get; set; }
        public string Name { get; set; }
    }

CodePudding user response:

If you want to bind the SelectedItem to the eventNumber property,

you should do SelectedItem="{Binding eventNumber}"

Of course, after you put the property eventNumber in the DataContext of the window

  • Related