kurakura88 kurakura88 - 3 months ago 18
C# Question

Binding Simple WPF TextBox Text TwoWay

I am very sorry that this question is very basic. I just learned WPF and I failed to make simple two way binding to textbox.text to string property.

XAML Code:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="StuInfo">
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="10,26,0,0" TextWrapping="Wrap" Text="{Binding Path=str,Mode=TwoWay}" VerticalAlignment="Top" Width="120"/>
<Button x:Name="button" Content="Check" HorizontalAlignment="Left" Margin="10,67,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
</Grid>




C# Code

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
str = "OK";
}

public string str { get; set; }

private void button_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine(str);
}
}


First, the textbox does not show "OK", but it is blank. Then, I typed a different text into the textbox, for ex:"blablabla" without the quotes. Then I click the button to check if my str property has been updated. Apparently, str still contains "OK".

What did I do wrong here? What did I miss to make the binding work?

Answer

The problem is that, you dont bind to codebehind of Window, but to DataContext.

Try this:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new DC();
    }

    public class DC
    {
        public string str { get; set; }

        public DC()
        {
            str = "OK";
        }
    }
}

Normally, you would have two different files, but for test, you can do it in one file. After that, your DC (DataContext) should implement INotifyPropertyChanged interface.

Try to find some article about MVVM like this http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial