friartuck
friartuck

Reputation: 3121

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>

Upvotes: 1

Views: 169

Answers (2)

Bolu
Bolu

Reputation: 8786

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}" ..../> 

Upvotes: 1

Sheridan
Sheridan

Reputation: 69959

You can't set both the DataContext and the Text property to the same value:

"{Binding Path=ResultList, Mode=OneWay}" 

You can try this:

<TextBlock Text="{Binding, Mode=OneWay}" DataContext="{Binding Path=ResultList}" />

But this might be better:

<TextBlock Text="{Binding Path=ResultList, Mode=OneWay}" />

Of course, it is hard to answer when you haven't provided all of the necessary information, such as what has been asked in the comments.

Upvotes: 0

Related Questions