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
  • 836
  • 8
  • 24
  • 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

4

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

You'll want to use the ABC object in your MainWindow.cs so you'll need to make that a public property and bind that to TextBox.Text. You'll also want to raise the ProperyChanged event on MyABC as well; you can figure that out using the link above. In the code-behind:

public ABC MyABC { get; set; }

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

And bind in XAML:

<TextBox x:Name="tb" Width="200" Text="{Binding Name, UpdateSourceTrigger="PropertyChanged"}"/>
evanb
  • 3,001
  • 18
  • 31