Question How can I bind the property of class Object with a textblock?

destro

Active member
Joined
Mar 28, 2020
Messages
36
Programming Experience
1-3
I have two classes in my script and an observable collection of secondary class type.



The method in the main class adds several objects of Person class type in an observable collection defined and initialized in primary class as follows:

C#:
 public class PrimaryClass : BaseViewModel
    {
      public ObservableCollection<Person> FamilyPeople { get; set; } 
      public PrimaryClass()
     {
     FamilyPeople = new ObservableCollection<Person>();
    AddPersons();
     }
      public void AddPersons()
        {
        
        FamilyPeople.Add(new Person{name = "Christine", Age = 14});
        FamilyPeople.Add(new Person{name = "Mike", Age = 32});
        FamilyPeople.Add(new Person{name = "Parero", Age = 38});
        
        }
    }
    public class Person
    {
         public String name
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;

        }
    }

I can bind a single unit using the index using following but can't figure out how to bind the name property of complete observable collection:

C#:
<Label x:Name="MahadashaPlanet" HorizontalAlignment="Left" Margin="528,105,0,0" VerticalAlignment="Top" Height="46" Width="129" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" FontWeight="Bold" FontSize="14" Content="{Binding Mahadashas[0].rulerName}"/>

I am trying to view all name property stored in an observable collection by binding it to the text block using following xaml binding but failed:

C#:
<TextBlock x:Name="ListNames" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Margin="528,151,0,0" Height="413" Width="283" TextAlignment="Center" Text="{Binding Source=FamilyPeople , Path=name}"/>


Can you tell me how to bind the names of person inside FamilyPeople?
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
2,409
Location
Chesapeake, VA
Programming Experience
10+
You can't bind multiple items into a control that represents only a single value. You can use a converter to convert the collection into a single string. Or you can do the right thing is use a control that actually handles multiple items to bind against a collection instead of trying to force fit a square peg into a round hole.
 

destro

Active member
Joined
Mar 28, 2020
Messages
36
Programming Experience
1-3
Or you can do the right thing is use a control that actually handles multiple items to bind against a collection instead of trying to force fit a square peg into a round hole.
So textBlock cannot handle multiple items? I thought it could. I also tried with list view. What control handle multiple items? I am sorry I am still learning to get myself familiar with xaml binding
 
Top Bottom