2

Maybe this is awfully wrong. I have a text box and want the value in that text box to be synchronized with a member of a class. I thought I use binding but I cannot get a handle on it. What I tried is below and does not work. Where am I thinking wrong?

Here is my XAML:

    <Window x:Class="tt_WPF.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:tt_WPF"
    Title="MainWindow" SizeToContent="WidthAndHeight">
    <StackPanel>
      <TextBox x:Name="tb" Width="200" Text="{Binding local:abc.Name}"></TextBox>
       <Button Click="Button_Click">Ok</Button>
    </StackPanel> </Window>

And here the code behind:

public class ABC
{
    public string Name { get; set; }
}
public partial class MainWindow : Window
{
    private ABC abc = new ABC();

    public MainWindow()
    {
        InitializeComponent();
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    { }
}
Johannes Schacht
  • 930
  • 1
  • 11
  • 28
  • If you don't want to use a MVVM toolset, consider how to implement INotifyPropertyChanged http://stackoverflow.com/questions/291518/inotifypropertychanged-vs-dependencyproperty-in-viewmodel And without tabbing out, the bound property might not update without addressing http://stackoverflow.com/a/25864134/3225 And, it's also quite typical to set the DataContext of the View/Window with the intance of the object you're binding to – kenny Jan 26 '15 at 22:21
  • 2
    Start reading the [Data Binding Overview](https://msdn.microsoft.com/en-us/library/ms752347.aspx) article on MSDN. – Clemens Jan 26 '15 at 22:28

1 Answers1

5

First, implement INotifyPropertyChanged and raise the property changed event on ABC.Name.

You'll want to set the ABC object in your MainWindow.cs as the data context and bind Name to TextBox.Text. In the code-behind:

public ABC MyABC { get; set; }

public MainWindow()
{
   InitializeComponent();
   MyABC = new ABC();
   DataContext = MyABC;
}

And bind in XAML:

<TextBox x:Name="tb" Width="200" Text="{Binding Name, UpdateSourceTrigger="PropertyChanged"}"/>
evanb
  • 3,061
  • 20
  • 32