WPF - Updated Runtime Related Issue

I am new to C # and new to WPF. This is probably a very simple question and a piece of cake for professionals. Please carry me.

I need to display a dynamic text block with changed text at runtime without additional triggers such as button clicks and so on. For some reason (my lack of understanding of the concept is obvious) the textblock remains empty.

Xaml is as simple as possible:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <Grid>
        <TextBlock Text="{Binding Path=Name}"/>
    </Grid>
</Window>

And the code behind it is simplified:

using System.ComponentModel;
using System.Threading;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Client client = new Client();
            client.Name = "Michael";
            Thread.Sleep(1000);
            client.Name = "Johnson";
        }
    }


    public class Client : INotifyPropertyChanged
    {
        private string name = "The name is:";
        public event PropertyChangedEventHandler PropertyChanged;

        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                if (this.name == value)
                    return;

                this.name = value;
                this.OnPropertyChanged(new PropertyChangedEventArgs("Name"));
            }
        }

        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, e);
        }
    }
}

Thanks in advance,

Wax

+3
source share
1 answer

, , DataContext , , .

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    Client client = new Client();

    // Set client as the DataContext.
    DataContext = client;

    client.Name = "Michael";
    Thread.Sleep(1000);
    client.Name = "Johnson";
}

TextBox.

, Thread.Sleep() , WPF DispatcherTimer, 1 .

, !

+4

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


All Articles