开发者

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.


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>


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> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜