<ListBox Name="guessListBox"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> </Style> </ListBox.ItemContainerStyle> <ListBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBlock Text="{Binding SuppliedGuess}" /> <TextBlock Grid.Column="1" DataContext="{Binding Word}" Text="{Binding Name}" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
We gave the ListBox a name so that we could easily set the ItemsSource of it, using guessListBox.ItemsSource = Guesses; Guesses is an ObservableCollection of Guess objects with the properties: string SuppliedGuess, Word Word, and several others which are not important for the purpose of our example. The Word object has the property string Name, and several others which are also not important for this tutorial.
You may notice that the first TextBlock has its Text attribute bound to SuppliedGuess, this means that the Text attribute automatically comes from a Guess's SuppliedGuess property as a collection of Guesses are supplied as the ListBox's ItemsSource.
However, for the second TextBlock it has a DataContext set. This is because the Text attribute automatically comes from the Name property of the Word which is a property of the ListBoxItem's Guess.
No comments:
Post a Comment