tags:

views:

200

answers:

4

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

+4  A: 

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.

Martin Harris
+2  A: 

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

arconaut
+1  A: 

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

Thomas Levesque
do you know what the xml for that would be?
Steve
your XAML is correct, you have to set the DataContext in code-behind
Thomas Levesque
+2  A: 

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

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

Jacob Adams
thanks, good to know
Steve