views:

22

answers:

2

I am trying with difficulty to use binding on an object which is contained in a list, so for example:

Class A
{
    IList<Class B> Items;
}

Class B
{
    string name;
}

I want to have in xaml for example

<Textblock Text="{Binding ClassA.Items[5].name}"/>

So any ideas? much appreciated

A: 

Using Indexers in a property path but each step of the path needs to be a property. Also each step needs to have public accessibility. Try changing to:-

public class ClassA   
{   
    public IList<ClassB> Items {get; set;}   
}   

public class ClassB   
{   
    public string Name {get; set;}   
}

Xaml:-

<Textblock Text="{Binding Items[5].Name}"/>  

Where the DataContextfor the TextBlock is an instance of type ClassA.

AnthonyWJones
A: 

For completeness sake, here's a complete working example if your interested. Properties must be public, and you'll need to refer to the instances of classes, rather than the class names.

This works in SL4+.

<UserControl x:Class="TestSilverlightStuff.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestSilverlightStuff"            
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<UserControl.Resources>
    <local:A x:Key="AData" />        
</UserControl.Resources>    
<Grid x:Name="LayoutRoot" Background="White"  >        
    <TextBlock 
               HorizontalAlignment="Left" 
               Text="{Binding Items[2].Name, Source={StaticResource AData}" 
               />
</Grid>
</UserControl>

and the C#:

using System.Collections.Generic;
using System.Windows.Controls;

namespace TestSilverlightStuff
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }

    public class A
    {        
        public A()
        {
            Items = new List<B>();
            Items.Add(new B() { Name = "WiredPrairie" });
            Items.Add(new B() { Name = "Microsoft" });
            Items.Add(new B() { Name = "Silverlight" });
            Items.Add(new B() { Name = ".NET" });
            Items.Add(new B() { Name = "Windows" });
            Items.Add(new B() { Name = "Overflow" });
        }

        public IList<B> Items 
        { 
            get; private set; 
        }
    }

    public class B
    {
        public string Name { get; set; }
    }
}

If you want to support more than a onetime binding (which is what's shown), you'll need to do more, like add INotifyPropertyChanged support to the "B" class.

WPCoder