Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you bind an Indexed property to a control in WPF

Tags:

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 ?????}" /> 
like image 898
Lance Avatar asked Nov 04 '09 02:11

Lance


People also ask

How do you bind property in XAML?

One-Way Data Binding The following XAML code creates four text blocks with some properties. Text properties of two text blocks are set to “Name” and “Title” statically, while the other two text blocks Text properties are bound to “Name” and “Title” which are class variables of Employee class which is shown below.

How many types of binding are there in WPF?

WPF binding offers four types of Binding. Remember, Binding runs on UI thread unless otherwise you specify it to run otherwise. OneWay: The target property will listen to the source property being changed and will update itself.

What is binding path in WPF?

Binding path syntax. Use the Path property to specify the source value you want to bind to: In the simplest case, the Path property value is the name of the property of the source object to use for the binding, such as Path=PropertyName . Subproperties of a property can be specified by a similar syntax as in C#.


1 Answers

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...

like image 63
itowlson Avatar answered Oct 19 '22 13:10

itowlson