4

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>
4thSpace
  • 43,672
  • 97
  • 296
  • 475

2 Answers2

2

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"/>
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
1

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.

Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
  • 1
    Thanks! You can also set the DataContext before the text assignment. – 4thSpace Feb 14 '14 at 18:06
  • Expanding on this example, do you have any idea why this scenario displays a blank window: http://stackoverflow.com/questions/21767121/how-to-bind-to-collection-2-deep? DataContext is now set but still nothing. – 4thSpace Feb 14 '14 at 18:18
  • @4thSpace: Please see my edit where I described an alternative for setting `DataContext`. Okay, I see this question. – Anatoliy Nikolaev Feb 14 '14 at 18:23