c# - WPF - 运行时更新绑定(bind)问题

标签 c# wpf runtime binding

我是 C# 的新手,也是 WPF 的新手。对于专业人士来说,这可能是一个非常基本的问题和小菜一碟。请耐心等待。

我需要显示一个动态文本 block ,其中文本在运行时更改,无需额外的触发器,例如按钮点击等。由于某种原因(显然我对这个概念的理解不足)文本 block 保持为空。

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

提前致谢

谷神星

最佳答案

为了使绑定(bind)工作,您需要将窗口的 DataContext 设置为您要绑定(bind)到的对象,在本例中为客户端对象。

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 秒延迟。

希望对您有所帮助!

关于c# - WPF - 运行时更新绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3484047/

相关文章:

c# - 过滤和 ICollectionView 过滤器 WPF

linux - 在 Linux/Bash 中测量程序执行时间的问题

function - 使用 powershell 更改运行时版本 azure 函数

mfc - 如何在运行时创建控件?

c# - 查找整数的集合位

c# - 使用 c#/htmlagilitpack 无法从 amazon.com 获取正确的信息

C# WebRequest 登录 session

c# - 我怎样才能只公开 IList<> 的一个片段?

c# - 将 httpWebRequest.Connection 设置为 "Closed"时出现 ArgumentException

c# - MVVM 列表框项上下文菜单