I have a button in my WPF application, on clicking it a new process is started. I want to keep the button disabled until the process is completed. Here I use BeginInvoke()
expecting the changes in IsEnabled
will be reflected in UI. However the button is always in enabled state.
MainWindow.xaml
<Window x:Class="ButtonTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ButtonTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Width="100" Height="30" Content="Start" IsEnabled="{Binding Path=IsEnabled}" Click="Button_Click"/>
</Grid>
</Window>
MainWindowViewModel.cs
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void SendPropertyChangedEvent(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
class MainWindowViewModel : ViewModelBase
{
private bool m_IsEnabled;
public bool IsEnabled
{
get { return m_IsEnabled; }
set
{
if (this.m_IsEnabled != value)
{
m_IsEnabled = value;
this.SendPropertyChangedEvent(nameof(this.IsEnabled));
}
}
}
}
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
this.DataContext = new MainWindowViewModel();
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
(DataContext as MainWindowViewModel).IsEnabled = false;
App.Current.Dispatcher.BeginInvoke(new Action(() => {
Correlate();
}));
}
private void Correlate()
{
Process process = new Process();
process.StartInfo.FileName = "test.exe";
process.Start();
process.WaitForExit();
(DataContext as MainWindowViewModel).IsEnabled = true;
}
}