0

I want to fill the text property from a textbox using binding. (My first try with binding).

I have this:

public string TestProperty { get; set; }

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    TestProperty = 'Test';
}

in xaml:

<TextBox x:Name="TextBox_Test" HorizontalAlignment="Left" Height="23" Margin="49,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="288" Text="{Binding ElementName=TextBox_Test, Path=TestProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

The property is filled when the form loads. The textbox keeps empty. How can i fill the textbox?

Hansvb
  • 113
  • 1
  • 1
  • 13

1 Answers1

0

You've got to fix a couple of things before this will work.

First, you're binding expression isn't quite right. You specified that the binding source is the TextBox by using the ElementName. That's not correct. Your source should actually be the Window since that's where your property exists. So, give your Window a name, and change ElementName to that Windowname. For example ..

<TextBox x:Name="TextBox_Test" HorizontalAlignment="Left" Height="23" Margin="49,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="288"
         Text="{Binding ElementName=Window_Test, Path=TestProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

Second, your Windowneeds to implement INotifyPropertyChangedfor changes on the source to be reflected on the target.

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _testProperty;

    public string TestProperty
    {
        get { return _testProperty; }
        set
        {
            _testProperty = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TestProperty"));
        }
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        TestProperty = "Test";
    }

    public MainWindow()
    {
        InitializeComponent();
    }
}

Note that I modified the class to implement the interface, and I raise the event in the property setter.

With these changes, your binding will work. I should note that this type of binding is a bit unusual. In cases like this, it's more common for the Window to use a DependencyProperty, or for you to bind to a non-UI class (A view model, for example). You may want to look into both as you learn about binding.

Dependency Properties

MVVM Pattern

Jason Tyler
  • 1,331
  • 13
  • 26