Reputation: 25
I have a problem with binding my ListView DataTemplate to an observablecollection that has a very nested property.
I've tried to bind using {Binding Trip.LegList.Leg.name}
but that doesn't work. What is the easiest way to bind something like this?
_currentTripData
is an ObservableCollection
of type Trip
.
<ListView Name="ui_tripview_triplist"
ItemsSource="{Binding _currentTripData}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding Trip.LegList.Leg.name}" />
</TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
That's how I tried to bind it in first place, but did not work. This is the classes I am using (converted from JSON).
public class Leg
{
public Origin Origin { get; set; }
public Destination Destination { get; set; }
public Stops Stops { get; set; }
public string name { get; set; }
}
public class LegList
{
public List<Leg> Leg { get; set; }
}
public class Trip
{
public List<ServiceDay> ServiceDays { get; set; }
public LegList LegList { get; set; }
}
It is kind of messy, but that is the objects I've been given to use...
Upvotes: 1
Views: 1762
Reputation: 547
There are a couple issues:
1) You are binding to an ObservableCollection of Trips, so you don't need to reference the Trip in the binding. You are already in a context of a Trip for each item.
2) LegList.Leg is a List which does not have a name property. You can add a nested ListView and bind the ItemSource to LegList.Leg (ie. {Binding LegList.Leg}
). Then bind to the name of each Leg.
<ListView Name="ui_tripview_triplist"
ItemsSource="{Binding _currentTripData}">
<ListView.ItemTemplate>
<DataTemplate>
<ListView ItemsSource="{Binding LegList.Leg}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding name}" />
</TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<DataTemplate>
</ListView.ItemTemplate>
</ListView>
Upvotes: 2
Reputation: 480
LegList is a list, so binding to Trip.LegList.Leg.name can't work. For example working would be Trip.LegList.Leg[0].name in your case. But I assume that is not what you want.
What I think you want to do is: Set the ItemsSource of your ListView to _currentTripData.LegList and the Binding to the Run to Text={Binding name}
Upvotes: 0