In the following example, how can I get:
- the button to be "disabled-grey"
- the message to say "working..."
while the work is being done, not after the work is done?
XAML:
<Window x:Class="TestIsEnabled8938.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel Margin="10" HorizontalAlignment="Left">
<Button x:Name="Button_Refresh"
HorizontalAlignment="Left"
DockPanel.Dock="Top"
Content="Refresh"
Click="Button_Refresh_Click"
Height="25"
Width="200"/>
<TextBlock x:Name="Message" Text="Button is ready to click."/>
</StackPanel>
</Window>
code-behind:
using System.Windows;
using System.Threading;
namespace TestIsEnabled8938
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Button_Refresh_Click(object sender, RoutedEventArgs e)
{
Message.Text = "working...";
Button_Refresh.IsEnabled = false;
//do work
Thread.Sleep(2000);
Message.Text = "Button is ready to click again.";
Button_Refresh.IsEnabled = true;
}
}
}
This doesn't work either:
Dispatcher.Invoke(new Action(() => { Message.Text = "working..."; }));
Dispatcher.Invoke(new Action(() => { Button_Refresh.IsEnabled = false; }));
Answer:
Thanks Heinzi, this code works:
using System.Windows;
using System.Threading;
using System.ComponentModel;
namespace TestIsEnabled8938
{
public partial class Window1 : Window
{
BackgroundWorker backgroundWorker;
public Window1()
{
InitializeComponent();
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (sender, args) =>
{
Thread.Sleep(3000);
};
backgroundWorker.RunWorkerCompleted += (sender, args) =>
{
Message.Text = "button is ready to click again";
Button_Refresh.IsEnabled = true;
};
}
private void Button_Refresh_Click(object sender, RoutedEventArgs e)
{
Message.Text = "working...";
Button_Refresh.IsEnabled = false;
backgroundWorker.RunWorkerAsync();
}
}
}