【发布时间】:2020-06-18 16:52:21
【问题描述】:
我需要在 Button_Click 方法中更新 UI。
当我在 Test = "sss"; ui 不会更新,但是当我继续直到方法完成时,它会更新 UI。
这是一个仅用于演示的简单场景,但在另一个示例中,我有一个 for 循环,它正在评估一长串对象,因此在 for 循环的整个评估过程中有几个更新。
如何在方法内更新ui而不是等到最后......
xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<TextBox Text="{Binding Path=Test}"></TextBox>
<Button Click="Button_Click">Click</Button>
</StackPanel>
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private string test;
public string Test { get { return test; } set { test = value; OnPropertyChanged("Test"); } }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
Test = "aaa";
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Test = "sss";
//do other stuff here
}
}
【问题讨论】:
-
您的断点或循环阻塞了 UI 线程,因此没有 UI 更新。您需要使更新异步,例如通过 DispatcherTimer 或等待某个异步方法的循环。
标签: c# wpf inotifypropertychanged