26

Given an instance of the class ThisClassShouldBeTheDataContext as the Datacontext for the view

class ThisClassShouldBeTheDataContext
{
  public Contacts Contacts {get;set;}
}

class Contacts
{
  public IEnumerable<Person> Persons {get;set;}
  public Person this[string Name]
  {
    get 
    {
      var p = from i in Persons where i.Name = Name select i;
      return p.First();
    }    
  }
}

class Person
{
  public string Name {get;set;}
  public string PhoneNumber {get;set;}
}

How can I bind Contact["John"].PhoneNumber to a textbox?

<TextBox Text="{Binding ?????}" />
Marwie
  • 3,177
  • 3
  • 28
  • 49
Lance
  • 2,774
  • 4
  • 37
  • 57

1 Answers1

37

The indexer notation is basically the same as C#:

<TextBox Text="{Binding Contacts[John].PhoneNumber}" />

See Binding Declarations Overview > Binding Path Syntax in MSDN for more info.

This won't, of course, work for arbitrary data types...

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
itowlson
  • 73,686
  • 17
  • 161
  • 157
  • 24
    What if my index is not a string, or it's from another property from the vm, say {Binding Contacts[ThisIsAnotherPropertyFromTheVm].PhoneNumber}. How can I do that? – Lance Nov 13 '09 at 10:30
  • 10
    It's been years since I asked the question in the comment when I was starting to use WPF, now I'm gonna answer it. I think the best way to do this is not to bind to an indexed property. Just expose another property where the getter will return the indexed property (i.e Contacts[ThisIsAnotherPropertyFromTheVm].PhoneNumber) – Lance Oct 02 '15 at 12:58