出力を表示するためのボタンとテキストボックスを単純に含む 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";
}
}