WPF Simple Object Binding

Im having some linking problems in wpf / xaml. This simple file has:

<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 text block to my "MyText" property. 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 run the text block you have no content - howcome?

+2


source to share


3 answers


you need the name of the element in your binding:



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

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

      

+2


source


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



0


source


There are several ways to do this. Probably the easiest one for something as simple as this form:

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

      

-1


source







All Articles