如何将Indexed属性绑定到WPF中的控件

时间:2009-11-04 02:22:43

标签: wpf xaml binding properties indexer

给定一个类ThisClassShouldBeTheDataContext的实例作为视图的Datacontext

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;}
}

如何将Contact["John"].PhoneNumber绑定到文本框?

<TextBox Text="{Binding ?????}" />

1 个答案:

答案 0 :(得分:29)

索引符号与C#基本相同:

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

有关详细信息,请参阅MSDN中的Binding Declarations Overview > Binding Path Syntax

当然,这不适用于任意数据类型......