I have a small WPF application. This application has a button that when clicked, should have its text changed and be disabled. The code for my button event handler is as follows:
/// <summary>
/// 'Read' button clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="routedEventArgs"></param>
private void ReadVersionNumber(object sender, RoutedEventArgs routedEventArgs)
{
Read.Content = "Reading....";
Read.IsEnabled = false;
SerialPort p = new SerialPort();
string response = "Could not read version";
try
{
// Do some stuff
}
catch (Exception)
{
response = "There was an error while reading the version number";
}
finally
{
Read.IsEnabled = true;
Read.Content = "Read";
if(p.IsOpen)
{
p.Close();
}
}
Version.Text = response;
}
The problem is my button text never changes, and it doesnt become disabled. Ive tried calling UpdateLayout after setting the button properties, but it still doesnt change. The button locks up while it runs through the method, then only updates its layout right at the end of the method. What do i need to do to update the layout?
In the finally (which ALWAYS executes) you set:
Further: if you change a property of a button multiple times in the same function that runs on the UI thread you will not see any changes because the updates will be too fast because the UI thread updates the UI AFTER the method has executed.
If you want to see the changes you could use a backgroundworker and in the ProgressChanged handler update the UI.