There is a class Person

public class Person { public string Name { get; set; } public string Images { get; set; } public string Age { get; set; } } 

There is xml file UsersList

  <?xml version="1.0" encoding="utf-8" ?> <users> <user name="Bill Gates"> <images>https://pbs.twimg.com/profile_images/558109954561679360/j1f9DiJi.jpeg</images> <age>48</age> </user> <user name="Larry Page"> <images>http://www.siliconbeat.com/wp-content/uploads/2015/06/page.jpg</images> <age>42</age> </user> </users> 

XAML file

 <ListBox x:Name="ListBox" Margin="36,10,273,0" > <ListBox.DataContext> <user:Person/> </ListBox.DataContext> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" > <Image Source="{Binding Images}" /> <TextBlock Text="{Binding Name}" /> <TextBlock Text="{Binding Age}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

code-behind

 public MainWindow() { InitializeComponent(); Load(); } public void Load() { Person user = new Person(); XmlDocument xDoc = new XmlDocument(); xDoc.Load("UsersList"); XmlElement xRoot = xDoc.DocumentElement; foreach (XmlNode xnode in xRoot) { if (xnode.Attributes.Count > 0) { XmlNode attr = xnode.Attributes.GetNamedItem("name"); if (attr != null) user.Name = attr.Value; } foreach (XmlNode childnode in xnode.ChildNodes) { if (childnode.Name == "images") { user.Images = childnode.InnerText; } if (childnode.Name == "age") { user.Age = childnode.InnerText; } } } } 

My question is how to properly bind the file data to XAML? I understand what can be done:

 Person user1 = new Person { Name = "Bill Gates", Age = 48, Images = "" }; Person user2 = new Person { Name = "Larry Page", Age = 42, Images = "" }; List<Person> users = new List<Person> { user1, user2 }; 

and everything will be cool, but if the list is 100 people, it’s not an option to manually enter. Yes, and edit and delete problematic.

  • And what prevents to fill in the List <Person> users in the Load function? And generally the strange Load method For Person user = new Person (); why are values ​​being reassigned in the foreach loop (XmlNode xnode in xRoot) you don't use it anywhere, why not add it to the users list at the end of the outer loop - user2455111
  • use the serializer, load the file and in the data context just make a property that will be a list of users. - Sergey
  • @ user2455111 the fact is that there are about 100 people on faces and it is necessary to foresee changes in the circle of people. As I understood from your words, in order to edit or add a person, I will have to edit the code-bend and compile the program. - Traid
  • one
    @ user2455111 Everything, figured out what you wrote: ListBox.itemsSource = users; - Traid

0