0

I send a property changed event for two different property values in the same block of code. In between is a Sleep Command. The Window does not update the property.

XAML:

 <TextBlock Text="{Binding ReferenceRunExecuting}" /> 

Code behind:

 ReferenceRunExecuting = true; Thread.Sleep(TimeSpan.FromSeconds(2)); ReferenceRunExecuting = false; 

Property:

 private bool _referenceRunExecuting = false; public bool ReferenceRunExecuting { get { return _referenceRunExecuting; } set { if (value != _referenceRunExecuting) { _referenceRunExecuting = value; OnPropertyChanged("ReferenceRunExecuting"); } } } 

OnPropertyChanged:

 public void OnPropertyChanged(string propertyChanged) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyChanged)); } 
3
  • 1
    When you say "The window does not update the property", do you mean, that you expect the value in the TextBox to change to True for two seconds then back to False? If yes, are you executing the the code in the code behind asynchronously? Commented Dec 20, 2019 at 12:25
  • Have you debugged to check the set method is being called properly? Commented Dec 20, 2019 at 12:28
  • How is the window supposed to update when you block the UI thread? Commented Dec 20, 2019 at 12:34

2 Answers 2

2

It looks like you are actually blocking the UI thread. It is not recommended to use Thread.Sleep as it will block. A blocked UI thread means a frozen UI.

You should wait asynchronously using Task.Delay:

private async Task WaitAsynchronously() { ReferenceRunExecuting = true; await Task.Delay(TimeSpan.FromSeconds(2)); ReferenceRunExecuting = false; } 

Also try to avoid string literals when possible as they are easily mistyped and make refactorings difficult (e.g. rename the property). Use nameof instead.

public bool ReferenceRunExecuting { get { return _referenceRunExecuting; } set { if (value != _referenceRunExecuting) { _referenceRunExecuting = value; OnPropertyChanged(nameof(this.ReferenceRunExecuting)); } } } 

Or take a look at CallerMemberNameAttribute:

public void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } 

and use it like

set { if (value != _referenceRunExecuting) { _referenceRunExecuting = value; OnPropertyChanged(); } } 
Sign up to request clarification or add additional context in comments.

Comments

0

The window cannot be updated when you block the UI thread that is supposed to be updated it. You need to sleep on a background thread or wait (sleep) asynchronously:

ReferenceRunExecuting = true; await Task.Delay(2000); ReferenceRunExecuting = false; 

ReferenceRunExecuting = true; Task.Run(()=> Thread.Sleep(TimeSpan.FromSeconds(2))) .ContinueWith(_ => ReferenceRunExecuting = false); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.