Search code examples
c#itemtemplate

Get the content of a textblock in a combobox.itemtemplate


I've managed to put different String Date into a ComboBox using TextBlock items with Data Binding, and then I'd like to get the text of the selected item in my ComboBox,here is my WPF code :

<ComboBox ItemsSource="{Binding ListProgram, ElementName=Window}" x:Name="date">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Name="test" Text="{Binding Date}"></TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

I tried this but it displayed nothing :

Console.WriteLine(date.Text);

I also tried this and it's still not working :

Console.WriteLine(test.Text);

Thanks a lot, a French beginner programmer.


Solution

  • date is a ComboBox so it's only natural for date.ToString() to return System.Windows.Controls.ComboBox.

    You want to get the value of the selected item of date which is not the control itself.

    First, you can omit the DataTemplate. strings get turned into TextBoxes automatically. Just specify the DisplayMemberPath and SelectedValuePath ("Date" in your case, but you can choose different properties of course) and WPF will take care of the rest.

    • DisplayMemberPath tells the ComboBox which property of the item to use to display the item.
    • SelectedValuePath tells the ComboBox which property to use for SelectedValue
    <ComboBox ItemsSource="{Binding ListProgram, ElementName=Window}"
        DisplayMemberPath="Date" SelectedValuePath="Date" x:Name="date">
    </ComboBox>
    

    In your code you can get the selected item (or it's value) with:

    date.SelectedValue // will return the "Date" property of the selected Item
    date.SelectedItem  // will return the item itself
    date.Text          // will return the string it is displaying