Search code examples
c#wpfbindingcomboboxtextblock

Bind combobox elements to data source


I have a combobox which hosts a textblock child element. I want to bind the textblock inside the combobox to a property called ResultList. I tried the code below, but it doesn't work. What have I missed out?

    <ComboBox x:Name="Test" HorizontalAlignment="Left" Margin="79,42,0,0" VerticalAlignment="Top" Width="344" 
              IsEditable="True">
        <ComboBox.Resources>
            <system:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">0</system:Double>
        </ComboBox.Resources>
        <ComboBox.ItemContainerStyle>
            <Style TargetType="{x:Type ComboBoxItem}" >
                <Setter Property="Background" Value="#FFFFFF"/>
                <Setter Property="BorderThickness" Value="0" />
            </Style>
        </ComboBox.ItemContainerStyle>
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=ResultList, Mode=OneWay}" DataContext="{Binding Path=ResultList, Mode=OneWay}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

Solution

  • So, to sum all the comments up:

    You need to bind the list to ItemsSource of comboBox.

    <ComboBox x:Name="Test" ItemsSrouce="{Binding ResultList}" ....>
    

    And set TextBlock in the ItemTemplate to something like:

    <TextBlock Text="{Binding Path=Age}" ..../> 
    <TextBlock Text="{Binding Path=Name}" ..../>