WPF - 运行时更新绑定问题

3

我对C#很生疏,对于WPF更是一无所知。这可能是一个非常基础的问题,对于专家来说是小菜一碟。请耐心等待我的提问。

我需要显示一个动态的文本块,在运行时更改文本而不需要额外的触发器,例如按钮单击等。由于某种原因(显然是我对概念理解不够),文本块仍然为空。

Xaml非常简单:

<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>

并且它背后的代码也被简化了:

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

1个回答

4
为了使绑定起作用,您需要将窗口的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成功更新。
只想指出,在loaded事件中使用Thread.Sleep()会导致程序在启动时停顿1秒钟,更好的方法是使用WPF DispatcherTimer 创建1秒延迟。
希望对你有所帮助!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接