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

Lan*_*nce 19 wpf xaml binding indexer properties

给定一个类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;}
}
Run Code Online (Sandbox Code Playgroud)

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

<TextBox Text="{Binding ?????}" />
Run Code Online (Sandbox Code Playgroud)

ito*_*son 29

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

<TextBox Text="{Binding Contacts[John].PhoneNumber}" />
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅MSDN中的绑定声明概述>绑定路径语法.

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

  • 如果我的索引不是字符串,或者来自vm的另一个属性,请说{绑定联系人[ThisIsAnotherPropertyFromTheVm] .PhoneNumber}.我怎样才能做到这一点? (21认同)
  • 当我开始使用WPF时,我在评论中提出问题已经好几年了,现在我要回答它.我认为最好的方法是不绑定索引属性.只需暴露另一个属性,其中getter将返回索引属性(即Contacts [ThisIsAnotherPropertyFromTheVm] .PhoneNumber) (5认同)