1

I have this ListBox:

<ListBox Name="lbAFiles" HorizontalAlignment="Left" Height="100" Margin="318,61,0,0" 
         VerticalAlignment="Top" Width="481">
    <ListBoxItem>
        <TextBlock>Line1<LineBreak/>Line2</TextBlock>
    </ListBoxItem>
</ListBox>

I have my own object with several properties that i want to fill inside my ListBox instead of the line:

<TextBlock>Line1<LineBreak/>Line2</TextBlock>

How can i do that with code behind ?

rut ray
  • 33
  • 2
  • Try looking in sample MVVM Projects will give you better understanding. Binding is a feature of WPF, ViewModel is nothing but a class which use to work for MVVM architecture. – Abin May 29 '15 at 22:41

1 Answers1

1
        lbAFiles.Items.Add("Line 1");
        lbAFiles.Items.Add("Line 2");

That said, it would be better to use MVVM and a ViewModel, but you asked how to do it in code behind.

Whatever the object you want to add there, you could pull the properties into the string you're adding.

Another (better) option would be to add this object directly to the ListBox, and use a DataTemplate to give it a "look" (otherwise you will just get the ToString value of that object).

And a much better option is to use data binding.

karfus
  • 869
  • 1
  • 13
  • 20
  • I am new with WPF so i sorry if this stupid question but what s the different between MVVM and a ViewModel and Data binding ? – rut ray May 29 '15 at 21:29
  • MVVM is a huge topic, but in short it's a design pattern where you keep the logical part of your View (e.g. XAML) inside of a separate class, called the ViewModel, which "models" the interactivity of the View. There's a good SO guide here: http://stackoverflow.com/questions/1405739/mvvm-tutorial-from-start-to-finish Data Binding is a way of attaching the data in your views directly to objects, and is an important facet of MVVM, though you can use it independently. It's all about separating your concerns to achieve "SOLID" design, which should benefit you in the long run. – karfus May 30 '15 at 02:16