【问题标题】:How can you bind an Indexed property to a control in WPF如何将索引属性绑定到 WPF 中的控件
【发布时间】:2010-12-12 21:13:45
【问题描述】:

给定 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 ?????}" />

【问题讨论】:

    标签: wpf xaml binding properties indexer


    【解决方案1】:

    索引器表示法与C#基本相同:

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

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

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

    【讨论】:

    • 如果我的索引不是字符串,或者它来自 vm 的另一个属性,例如 {Binding Contacts[ThisIsAnotherPropertyFromTheVm].PhoneNumber},该怎么办。我该怎么做?
    • 当我开始使用 WPF 时,我已经有好几年没有在评论中提出这个问题了,现在我来回答一下。我认为最好的方法是不要绑定到索引属性。只需公开另一个属性,getter 将返回索引属性(即 Contacts[ThisIsAnotherPropertyFromTheVm].PhoneNumber)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多