Kroetenwurz Kroetenwurz - 1 year ago 84
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;
this.AreButtonsEnabled = true;


<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?


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")); }

I am bound to .Net 3.5.

Answer Source

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;      
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download