Why does not TextBlock communicate?

When I run this simple wpf application, 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>
+4
source share
2 answers

You must install DataContext:

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

Alternatively, you can install DataContexton the XAML side as follows:

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, an interface must be implemented to update the property for the class INotifyPropertyChanged.

+1
source

DataContext is a way, but you can also use the RelativeSourcemarkup extension to get the window property:

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

Source: https://habr.com/ru/post/1526998/


All Articles