Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 555
user776676 Avatar asked Oct 10 '22 18:10

user776676


2 Answers

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>
like image 158
Kirk Broadhurst Avatar answered Oct 13 '22 12:10

Kirk Broadhurst


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> 
like image 40
Jens Avatar answered Oct 13 '22 12:10

Jens