A
A
Anton2016-01-06 21:04:02
WPF
Anton, 2016-01-06 21:04:02

How to populate a ListBox with an ItemTemplate (WPF)?

Hello!
There is a ListBox:

<ListBox x:Name="myListBox" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="500" Margin="10,10,0,0" VerticalAlignment="Top" Width="420" ItemTemplate="{DynamicResource NewsDataTemplate}"/>

The NewsDataTemplate has lines like this:
<TextBlock Text="{Binding Path=Title, FallbackValue=Title}" />

How can I populate this ListBox by passing the contents of the required variables to each new element?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MonkAlex, 2016-01-06
@hummingbird

xaml, setting DataType="local:Line" is optional.

<ListBox ItemsSource="{Binding}">
            <ListBox.ItemTemplate>
                <DataTemplate DataType="local:Line">
                    <TextBlock Text="{Binding Title}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

setting the binding in the form code:
public MainWindow()
    {
      InitializeComponent();
      var lines = new List<Line>();
      lines.Add(new Line() { Title = "1" });
      lines.Add(new Line() { Title = "2" });
      lines.Add(new Line() { Title = "3" });
      this.DataContext = lines;
    }

Well, the code of the Line class:
public class Line
  {
    public string Title { get; set; } 
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question