4thSpace
4thSpace

Reputation: 44312

Why doesn't TextBlock bind?

When I run this simple wpf app, I get a blank window. Any ideas what I'm doing wrong?

//MainWindow.xaml.cs
public string SimpleText {get;set;}
public MainWindow()
{
  InitializeComponent();
  SimpleText = "this is a test";
}

//MainWindow.xaml
<StackPanel>
  <TextBlock Text="{Binding SimpleText}" Width="200"/>
</StackPanel>

Upvotes: 4

Views: 58

Answers (2)

Anatoliy Nikolaev
Anatoliy Nikolaev

Reputation: 22702

You must set the DataContext:

public MainWindow()
{
    InitializeComponent();
    SimpleText = "this is a test";
    this.DataContext = this;
}

As an alternative, you can set DataContext on the side XAML like this:

XAML

<Window x:Class="TextBlockDontBind.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:this="clr-namespace:TextBlockDontBind"
    Title="MainWindow" Height="350" Width="525">

    <Window.DataContext>
        <this:TestData />
    </Window.DataContext>

    <StackPanel>
        <TextBlock Text="{Binding SimpleText}" Width="200"/>
    </StackPanel>
</Window>

Code-behind

public class TestData
{
    private string _simpleText = "this is a test";

    public string SimpleText
    {
        get
        {
            return _simpleText;
        }

        set
        {
            _simpleText = value;
        }
    }
}

But in this case to update a property, for a Class must implement the INotifyPropertyChanged interface.

Upvotes: 1

Rohit Vats
Rohit Vats

Reputation: 81253

DataContext is a way to go but you can also use RelativeSource markup extension to get window's property:

<TextBlock Text="{Binding SimpleText, RelativeSource={RelativeSource
                          Mode=FindAncestor, AncestorType=Window}}" Width="200"/>

Upvotes: 2

Related Questions