Orionlk
Orionlk

Reputation: 278

Binding string to a TextBlock WPF - What I'm doing wrong?

I read some threads which explain binding on WPF, but when I wrote that code, it doesn't bind me the string to my TextBlock, and I did not know why.

Help?

XAML

        <TextBlock x:Name="myTextBlock"
               Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />

C#

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        _name = "Jones";
        myTextBlock.DataContext = Name;          
    }

    private string _name;
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }

    // property changed event
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

Upvotes: 1

Views: 1627

Answers (2)

yo chauhan
yo chauhan

Reputation: 12295

set

myTextBlock.DataContext = Name; 

to

myTextBlock.DataContext = this; 

it would be better you set DataContext of MainWindow to this instead of setting the DataContext of TextBlock. like

InitializeComponent();
    _name = "Jones";
    this.DataContext = this; 

otherwise you will need to set the DataContext of each cotrol you will use in the Window.

Binding finds the specified Path(here Name in your case) in the DataContext using Reflection. So your Name Property is in MainWindow class, so you need to set DataContext to instance of your MainWindow class.

Update Change property name from Name to some other property name because this property name already exist in Window class that MainWindow is inheriting, and it tries to bind that property .

Upvotes: 3

St&#237;gandr
St&#237;gandr

Reputation: 2902

In your ctor set as stated above

this.DataContext = this;

Nasty codebehind. Hmm I can't test right now,the updatesourcetrigger should update your your property each time you enter a key. Add Mode=TwoWay.

<TextBlock x:Name="myTextBlock" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />

Upvotes: 4

Related Questions