我有一个WPF应用程序,简单地包含一个按钮和一个文本框以显示一些输出内容。当用户单击按钮时,线程启动禁用按钮,将输出内容打印到文本框,然后线程停止(此时我希望按钮重新启用)。
应用程序似乎正确地禁用了按钮,并更新了文本框。但是,当线程完成时,它总是无法正确地重新启用按钮!有人能告诉我我做错了什么吗?
这是我的XAML片段:
这是我的ViewModel代码(我使用Josh Smith的MVVM设计):
应用程序似乎正确地禁用了按钮,并更新了文本框。但是,当线程完成时,它总是无法正确地重新启用按钮!有人能告诉我我做错了什么吗?
这是我的XAML片段:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0" HorizontalAlignment="Center" Command="{Binding ExecuteCommand}">E_xecute</Button>
<Label Grid.Row="1" Content="Output Window:" HorizontalAlignment="Left"/>
<TextBlock Grid.Row="2" Text="{Binding Output}"/>
</Grid>
这是我的ViewModel代码(我使用Josh Smith的MVVM设计):
public class WindowViewModel : ViewModelBase
{
private bool _threadStopped;
private RelayCommand _executeCommand;
private string _output;
public WindowViewModel()
{
_threadStopped = true;
}
public string Output { get { return _output; } set { _output = value; OnPropertyChanged("Output"); } }
public ICommand ExecuteCommand
{
get
{
if (_executeCommand == null)
{
_executeCommand = new RelayCommand(p => this.ExecuteThread(p), p => this.CanExecuteThread);
}
return _executeCommand;
}
}
public bool CanExecuteThread
{
get
{
return _threadStopped;
}
set
{
_threadStopped = value;
}
}
private void ExecuteThread(object p)
{
ThreadStart ts = new ThreadStart(ThreadMethod);
Thread t = new Thread(ts);
t.Start();
}
private void ThreadMethod()
{
CanExecuteThread = false;
Output = string.Empty;
Output += "Thread Started: Is the 'Execute' button disabled?\r\n";
int countdown = 5000;
while (countdown > 0)
{
Output += string.Format("Time remaining: {0}...\r\n", countdown / 1000);
countdown -= 1000;
Thread.Sleep(1000);
}
CanExecuteThread = true;
Output += "Thread Stopped: Is the 'Execute' button enabled?\r\n";
}
}