user776676
user776676

Reputation: 4385

How to do datatemplate for items in listbox?

I have an XML file (see below) and can display all the Product Names in a listbox. I want each entry in the listbox to display Product Name followed by Price, not just Product Name.

How do I do the datatemplate in the XAML file? Thanks.

Simplified XML file:

<Product> 
<Name>Red Chair</Name> 
<Price>29.5</Price>  
</Product>

Simplified XAML file:

<DockPanel>      
<ListBox Name="listBox1" ItemsSource="{Binding}" Margin="10" >      
</ListBox> 
</DockPanel> 

In my C# file, I use LINQ to collect the products from the XML file and assign var products to listBox1.DataContext and it works fine. Now I just want to add in the Price. Thanks.

Upvotes: 5

Views: 286

Answers (2)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28728

You do this the same as any other ItemTemplate.

Make sure that you're binding to the Product, not the Name. You can then select the values from the XML using XPath, something like this.

<DockPanel>
  <ListBox Name="listBox1" 
           ItemsSource="{Binding}" 
           Margin="10" >       
    <ListBox.ItemTemplate>
      <DataTemplate>
        <StackPanel>
          <TextBlock Text={Binding XPath=./Name} />
          <TextBlock Text={Binding XPath=./Price} />
        </StackPanel>
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>
</DockPanel>

Upvotes: 2

Jens
Jens

Reputation: 25583

Assuming your ItemsSource is of type IEnumerable<Product>, with

class Product
{
    public string Name { get; set; }
    public double Price { get; set; }
}

you can set the item template like this:

<ListBox Name="listBox1" ItemsSource="{Binding}" Margin="10" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text = "{Binding Name}" />
                <TextBlock Text = "{Binding Price, StringFormat=f2}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox> 

Upvotes: 2

Related Questions