我有一个 WPF 应用程序,它只包含一个按钮和一个文本框来显示一些输出。当用户单击按钮时,将启动一个禁用按钮的线程,将内容打印到输出文本框,然后线程停止(此时我希望再次启用按钮)。
该应用程序似乎正确禁用了按钮,并正确更新了文本框。但是,当线程完成时,它总是无法正确地重新启用按钮!谁能告诉我我做错了什么?
这是我的 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";
}
}