C# WPF-运行时更新的绑定问题
我是C#方面的新手,对WPF完全是新手。对于职业选手来说,这可能是一个非常基本的问题,也是小菜一碟。请容忍我 我需要显示一个动态文本块,其中的文本在运行时发生更改,而不需要额外的触发器,例如按钮单击等。由于某种原因(我对这个概念显然理解不足),textblock保持为空 Xaml尽可能简单:C# WPF-运行时更新的绑定问题,c#,wpf,runtime,binding,C#,Wpf,Runtime,Binding,我是C#方面的新手,对WPF完全是新手。对于职业选手来说,这可能是一个非常基本的问题,也是小菜一碟。请容忍我 我需要显示一个动态文本块,其中的文本在运行时发生更改,而不需要额外的触发器,例如按钮单击等。由于某种原因(我对这个概念显然理解不足),textblock保持为空 Xaml尽可能简单: <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/
<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>
提前感谢,
Ceres为了使绑定工作,您需要将窗口的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";
}
这将导致文本框成功更新
需要指出的是,在加载的事件中使用Thread.Sleep()会导致程序在启动时挂起一秒钟,更好的方法是使用WPF创建1秒延迟
希望有帮助
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";
}