Bind XAML elements to entities TwoWay

Mohsen picture Mohsen · Dec 19, 2011 · Viewed 11.2k times · Source

I want to bind an entity property (say Salary) to a property of a XAML element (like a TextBox.Text) and use this binding to save Text of TextBox to salary field which is bound as a entity property to 'Text' of some TextBox.

Something like the following :

<Grid DataContext="Employee">
    <TextBox Text="{Binding Path=Salary, Mode=TwoWay}"/>
</Grid>

Answer

blindmeis picture blindmeis · Dec 19, 2011

you just can bind Properties in xaml - so your salary have to be a property and not a field. if your Employee is the class with the salary you can set datacontext to an instance of it. you can do it in xaml or codebehind or with binding.

public class Employee //implement INotifyPropertyChanged to get the power of binding :)
{
    public decimal Salary {get;set}
}

view.xaml

<Grid>
 <Grid.DataContext>
        <local:Employee/>
  </Grid.DataContext>
   <TextBox Text="{Binding Path=Salary, Mode=TwoWay}"/>
 </Grid>

you can set the datacontext in many ways