H4mm3rHead
H4mm3rHead

Reputation: 583

WPF Simple Binding to an objects property

Im having some problems with binding in wpf/xaml. Have this simple file:

<Window x:Class="test.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <TextBlock Height="21" Foreground="Black" Margin="74,98,84,0" Name="textBlock1" VerticalAlignment="Top" Text="{Binding MyText}" />
    </Grid>
</Window>

Where i want to bind the content of the textblock to my property "MyText". My code looks like this:

 public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        public string MyText
        {
            get { return "This is a test"; }
        }
    }

All in all very simple, but when i start the textblock has no content - howcome?

Upvotes: 2

Views: 2929

Answers (3)

Shaun Bowe
Shaun Bowe

Reputation: 10008

There are a number of ways to accomplish this. Probably the easiest for something as simple as this form is:

public Window1()
{
    InitializeComponent();
    this.DataContext = this;
}

Upvotes: -1

jturinetti
jturinetti

Reputation: 169

If I'm remembering my WPF binding syntax correctly, I believe your binding expression should read Text="{Binding Path=MyText}"

Upvotes: 0

Muad&#39;Dib
Muad&#39;Dib

Reputation: 29256

you need an element name in your binding:

<Window ... x:Name="ThisWindow"...>

        <TextBlock ... Text="{Binding MyText, ElementName=ThisWindow}" />

Upvotes: 4

Related Questions