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 ?????}" />
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.
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.
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#.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With