如何在WPF中将索引属性绑定到控件

26

将ThisClassShouldBeTheDataContext类的一个实例作为视图的数据上下文

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个回答

38

24
如果我的索引不是一个字符串,或者它来自于vm的另一个属性,比如{Binding Contacts[ThisIsAnotherPropertyFromTheVm].PhoneNumber}。我该怎么办? - Lance
10
自从我开始使用 WPF 时在评论中提出了这个问题,已经过去了好几年,现在我要来回答它。我认为最好的方法不是绑定到一个索引属性,而是暴露另一个属性,在该属性的 getter 中返回索引属性的值(即 Contacts[ThisIsAnotherPropertyFromTheVm].PhoneNumber)。 - Lance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接