Steve
Steve

Reputation: 12034

DataBind to a textbox in WPF

I'm completely new to databinding in WPF, and I'm trying to bind an object property to a textbox. My object is

public class TestObj
{
    private m_Limit;

    public string Limit
    {
       get 
        {
         return m_Limit;
        }
        set
        {
          m_Limit = value;
        }
    }

My XAML looks like

<Window x:Class="NECSHarness2.UpdateJobParameters"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tools="clr-namespace:ManagementObjects;assembly=Core"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="Update Job Parameters" Height="320" Width="460">
<Grid>
    <TextBox Text ="{Binding Path = Limit, Mode = TwoWay}" Height="20" HorizontalAlignment="Right" Margin="0,48,29,0" Name="textBox3" VerticalAlignment="Top" Width="161" />
   </Grid>

Now, obviously I'm not setting the source anywhere, and I'm very confused. I got this to work with a listview, but now I'm stumped. Thanks for any help.

Upvotes: 2

Views: 22026

Answers (4)

Jacob Adams
Jacob Adams

Reputation: 4004

For TwoWay binding to work your object also has to implement INotifyPropertyChanged

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

Upvotes: 2

Thomas Levesque
Thomas Levesque

Reputation: 292685

Unless specified otherwise, the source of a binding is always the DataContext of the control. You have to set the DataContext for your form to the TestObj instance

Upvotes: 2

arconaut
arconaut

Reputation: 3285

If you don't specify binding's Source, RelativeSource or ElementName the Binding uses control's DataContext. The DataContext is passed through the visual tree from upper element (e.g. Window) to the lower ones (TextBox in your case).

So WPF will search for the Limit property in your Window class (because you've bound the window's DataContext to the window itself).

Also, you may want to read basics about DataBinding in WPF: http://msdn.microsoft.com/en-us/library/ms750612.aspx

Upvotes: 2

Martin Harris
Martin Harris

Reputation: 28627

You need to set the DataContext. Either in the code behind:

textBox3.DataContext = instanceOfTestObj;

Or using an object data provider

  <Window.Resources>
    <src:TestObj x:Key="theData" Limit="Wibble" />
  </Window.Resources>

  <TextBox Text="{Binding Source={StaticResource theData}..../>

There is a nice introduction to databinding in more depth here.

Upvotes: 7

Related Questions