Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 341
Steve Avatar asked Jan 29 '26 01:01

Steve


2 Answers

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.

like image 121
Martin Harris Avatar answered Jan 31 '26 14:01

Martin Harris


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

like image 23
arconaut Avatar answered Jan 31 '26 13:01

arconaut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!