Search code examples
c#wpfcomboboxdropdownitemtemplate

WPF Getting selected option of combobox item template


I populate my Combobox with textblocks via a datatemplate, since this was the most direct way i could find to populate the dropdown box with a list of variables. However, now that I am trying to read the value or selected option, I have no idea how to tackle it. All other topics recommend "SelectedValue.ToString();" or the likes, but this just returns the first line of my XAML..

My Xaml;

<ComboBox Name="DropdownDansen" Grid.Column="1" Grid.Row="2" Margin="5" 
Grid.ColumnSpan="2" SelectedValue="{Binding dans}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding dans}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

my cs:

    public List<Person> people = new List<Person>();

        public MainWindow()
        {
            InitializeComponent();
            people.Add(new Person { id = "0", dans = "Tango", teamlid1 = "Daniel 
", teamlid2 = "Sabrina ", coach = "Hans van Bommel" });
            people.Add(new Person { id = "1", dans = "Wals", teamlid1 = "de Ridder", teamlid2 = "Aninka ", coach = "Hans van Bommel" });
            people.Add(new Person { id = "2", dans = "Foxtrot", teamlid1 = "de Ridder", teamlid2 = "de Ridder", coach = "Hans van Bommel" });
            people.Add(new Person { id = "3", dans = "Quickstep", teamlid1 = "de Ridder", teamlid2 = "de Ridder", coach = "Dansschool van Amersfoort" });

            DropdownDansen.ItemsSource = people;
            displayDans.DataContext = new DisplayText() { deDans = "chachacha" 
    };
            displaylid1.DataContext = new DisplayText() { lid1 = "Kees" };
            displaylid2.DataContext = new DisplayText() { lid2 = "Hariette" };
            displaycoach.DataContext = new DisplayText() { deCoach = "Steve" };
        }

        public class Person
        {
            public string id { get; set; }
            public string dans { get; set; }
            public string teamlid1 { get; set; }
            public string teamlid2 { get; set; }
            public string coach { get; set; }

        }

Edit: The answer provided by @mm8 does quite the trick! However, with the combobox updated, the dropdown menu is filled with the first line of my xaml instead! screenshot of project

 <ComboBox Name="DropdownDansen" Grid.Column="1" Grid.Row="2" Margin="5" Grid.ColumnSpan="2" SelectedValue="{Binding dans}" SelectedValuePath="dans"/>

Solution

  • Cast SelectedItem to a Person:

    Person selectedPerson = DropdownDansen.SelectedItem as Person;
    if (selectedPerson != null)
    {
        string dans = selectedPerson.dans;
    }
    

    For your binding (SelectedValue="{Binding dans}") to work, dans should be a string property of the DataContext of the ComboBox and you should also set the SelectedValuePath property to "dans":

    <ComboBox Name="DropdownDansen" ... SelectedValue="{Binding dans}" SelectedValuePath="dans">