DavidG DavidG - 2 months ago 11
C# Question

C# WPF Button is not switching from disabled to enabled

I finally got rid of all the error messages as I attempted ways to find a control and enable it.

In the properties pane I disabled a button on mainwindow.

This code runs successfully, albeit annoyingly, because every second I have it give me another msgbox to show code is being triggered. But it is not enabling the button. I'm new to C# so it looks like arabic to me. In VB it would just be:

btnMyButton.Enabled = True


Here is my code behind:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
System.Timers.Timer myTimer = new System.Timers.Timer();
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = 1000; // 1000 ms is one second
myTimer.Start();
}

public void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
DateTime now = DateTime.Now;
DateTime today3am = now.Date.AddHours(3);

if (DateTime.Today == today3am.Date && now >= today3am)
{
MessageBox.Show("Code is being triggered");
btnMyButton.IsEnabled = true;
}
}
}


As per responses I also tried:

public void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
DateTime now = DateTime.Now;
DateTime today3am = now.Date.AddHours(3);

if (DateTime.Today == today3am.Date && now >= today3am)
{
MessageBox.Show("Button Should Enable");
this.Dispatcher.Invoke(() => {
btnMyButton.IsEnabled = true;
});
}
}

Answer

Try to use Dispatcher. It may be that the GUI blocks up the change of controls from Code. The Dispatcher coordinates the access to an element from multiple threads:

this.Dispatcher.Invoke(() => {
    btnMyButton.IsEnabled = true;
});