Search code examples
c#xamlwindows-phone-8data-binding

Multi level data Binding in Windows Phone 8


I am a beginner in Windows phone programming.

I want to bind the data from API to my XAML elements using that Binding Attributes. Please let me know how can we bind multilevel classes objects in it.

Here's my scenario.

List<Sample> SearchResult = new List<Sample>()
{
    new Sample(){
         Name="ABC",                                  
         modelProperty = new SampleDetail(){ 
               articleNo="1", videoURL = "https://www.youtube.com/watch?v=abc",
               colors = new List<ColorsDemo>(){ 
                         new ColorsDemo { 
                               Name = "Red",
                               colorProperty= new ColorDemoProperty{ name = "ABC",article_no = "Art1",
                               image = new Uri("http://img.youtube.com/vi/e60E99tUdxs/default.jpg",UriKind.RelativeOrAbsolute) 
                               }
                         }
               }
         }
}

And now, I want to bind the Name of ColorsDemo class into my textblock. See what I have done to bind in XAML like this:

<TextBlock x:Name="PName" Grid.Row="0" Margin="100,0,0,0" Tap="ProductName_Tap" HorizontalAlignment="Center" VerticalAlignment="Center" Width="350" TextWrapping="Wrap" Foreground="Black" Text="{Binding Path=modelProperty.colors.Name}" FontSize="30"></TextBlock>

Solution

  • From your code, i see that colors is a List of ColorDemo objects. So when you say {Binding Path=modelProperty.colors.Name}it does not tell which list item to bind to. The correct usage should be {Binding Path=modelProperty.colors[0].Name}. This tells the control to bind to the name of the first color item (as index is 0).

    To bind all the colors. You should use a Listview and bind the colors in it. So you should be able to do something like this.

    <ListView ItemSource={Binding Path=modelProperty.colors}>
        <ListView.ItemTemplate>
            <TextBlock x:Name="PName" Grid.Row="0" Margin="100,0,0,0" Tap="ProductName_Tap" HorizontalAlignment="Center" VerticalAlignment="Center" Width="350" TextWrapping="Wrap" Foreground="Black" Text="{Binding Path=Name}" FontSize="30"></TextBlock>
        </ListView.ItemTemplate>
    </ListView>