Kroetenwurz Kroetenwurz - 1 month ago 6
C# Question

How to properly disable buttons temporarily in a WPF application?

I am fairly new to WPF and still looking for an easy solution to temporarily deactivate the buttons in my application. Here is what I am doing:

Button Click:

private void Calculate_Click(object sender, RoutedEventArgs e)
{
this.AreButtonsEnabled = false;
System.Threading.Thread.Sleep(1000);
this.AreButtonsEnabled = true;
}


XAML:

<Button x:Name="OtherButton" IsEnabled="{Binding AreButtonsEnabled}" Content="OtherButton" HorizontalAlignment="Left" Margin="165,152,0,0" VerticalAlignment="Top" Width="75"/>


The binding works as expected, but if I activate and deactivate the buttons in this one call, the deactivation is not done. How do I get the GUI to properly deactivate the buttons?

EDIT

The notification event (that works fine):

public partial class MainWindow : Window, INotifyPropertyChanged
{

private bool areButtonsEnabled;
public bool AreButtonsEnabled
{
get { return this.areButtonsEnabled; }
set { areButtonsEnabled = value; OnPropertyChanged(new PropertyChangedEventArgs("AreButtonsEnabled")); }
}


Note
I am bound to .Net 3.5.

Answer

It might be better to disable the buttons and then start/use another thread to do the work and enable the buttons at the end (one way to do that in one method is by using async/await) that way the UI will remain responsible and up to date.

Pseudo code:

private async void Calculate_Click(object sender, RoutedEventArgs e)
{
    AreButtonsEnabled = false;
    await Task.Run(()=>DoWork());
    AreButtonsEnabled = true;      
}