views:

59

answers:

1

Hello everyone! I'm quite a novice with C# and a complete newbie regarding WPF. Probably it's a very basic question and piece of cake for the pros. Please bear with me.

I need to display a dynamic textblock with text changed in run time without additional triggers such as button clicks and so. For some reason (my insufficient understanding of the concept obviously) textblock stays empty.

Xaml is as simple as it can be:

<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 simplified as well:

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,

Ceres

+2  A: 

In order for the binding to work you need to set the DataContext of the window to the object you want to bind to, in this instance the client object.

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";
}

This should cause the TextBox to successfully update.

Just to point out that using Thread.Sleep() in the loaded event causes the program to hang for a second on startup, a better idea would be to use the WPF DispatcherTimer to create the 1 second delay.

Hope that helps!

Fara
It does! Thanks a lot!
Ceres