我在同一代码块中为两个不同的属性值发送属性更改事件。介于两者之间的是睡眠命令。窗口不会更新属性。
XAML:
<TextBlock Text="{Binding ReferenceRunExecuting}" />
代码隐藏:
ReferenceRunExecuting = true;
Thread.Sleep(TimeSpan.FromSeconds(2));
ReferenceRunExecuting = false;
财产:
private bool _referenceRunExecuting = false;
public bool ReferenceRunExecuting
{
get { return _referenceRunExecuting; }
set
{
if (value != _referenceRunExecuting)
{
_referenceRunExecuting = value;
OnPropertyChanged("ReferenceRunExecuting");
}
}
}
属性已更改:
public void OnPropertyChanged(string propertyChanged)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyChanged));
}
看起来您实际上正在阻止 UI 线程。不建议使用Thread.Sleep
因为它会阻塞。被阻止的 UI 线程意味着冻结的 UI。
您应该使用Task.Delay
异步等待:
private async Task WaitAsynchronously()
{
ReferenceRunExecuting = true;
await Task.Delay(TimeSpan.FromSeconds(2));
ReferenceRunExecuting = false;
}
还要尽可能避免使用字符串文字,因为它们很容易键入错误并使重构变得困难(例如重命名属性(。请改用nameof
。
public bool ReferenceRunExecuting
{
get { return _referenceRunExecuting; }
set
{
if (value != _referenceRunExecuting)
{
_referenceRunExecuting = value;
OnPropertyChanged(nameof(this.ReferenceRunExecuting));
}
}
}
或者看看CallerMemberNameAttribute
:
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
并像使用它一样使用
set
{
if (value != _referenceRunExecuting)
{
_referenceRunExecuting = value;
OnPropertyChanged();
}
}
当您阻止应该更新它的 UI 线程时,无法更新该窗口。您需要在后台线程上休眠或异步等待(睡眠(:
ReferenceRunExecuting = true;
await Task.Delay(2000);
ReferenceRunExecuting = false;
ReferenceRunExecuting = true;
Task.Run(()=> Thread.Sleep(TimeSpan.FromSeconds(2)))
.ContinueWith(_ => ReferenceRunExecuting = false);