5

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

2 に答える 2

1

コマンドの実行可能状態が変更されたことをWPFが認識できるようにする必要があります。これを行う簡単な方法は次のとおりです。

CommandManager.InvalidateRequerySuggested()

CanExecuteThread内:

set
{
    _threadStopped = value;
    CommandManager.InvalidateRequerySuggested()
}

編集(今は時間があります):実際の問題は、CanExecuteThreadプロパティが変更されたときに通知されていない可能性があります。PropertyChangedWPFが変更を検出するには、次の値を上げる必要があります。

public bool CanExecuteThread
{
    get { return _threadStopped; }
    set
    {
        if (_threadStopped != value)
        {
            _threadStopped = value;
            this.OnPropertyChanged(() => this.CanExecuteThread);
        }
    }
}

上記は、ViewModel基本クラスにOnPropertyChangedメソッドがあることを前提としています。

BackgroundWorkerそうは言っても、 :を使用するだけで物事を単純化できることも指摘したいと思います。

public class WindowViewModel : ViewModel
{
    private readonly BackgroundWorker backgroundWorker;

    public WindowVieWModel()
    {
        backgroundWorker = new BackgroundWorker();
        backgroundWorker.DoWork += delegate
        {
            // do work here (what's currently in ThreadMethod)
        };
        backgroundWorker.RunWorkerCompleted += delegate
        {
            // this will all run on the UI thread after the work is done
            this.OnPropertyChanged(() => this.CanExecuteThread);
        };
    }

    ...

    public bool CanExecuteThread
    {
        get { !this.backgroundWorker.IsBusy; }
    }

    private void ExecuteThread(object p)
    {
        // this will kick off the work
        this.backgroundWorker.RunWorkerAsync();

        // this property will have changed because the worker is busy
        this.OnPropertyChanged(() => this.CanExecuteThread);
    }
}

これをさらにリファクタリングしてさらに良くすることもできますが、アイデアは得られます。

于 2010-08-02T18:18:09.080 に答える
0

Kent Boogaartによって提案されたように、これが答えであり、それは機能します。基本的に、UIスレッドでCommandManager.InvalidateRequerySuggestedを、Dispatcherのinvoke呼び出し内に配置して呼び出す必要がありました。また、このソリューションでは不要になったため、CanExecuteThreadプロパティのSetアクセサーを削除できたことにも注意してください。ありがとう、ケント!

public class WindowViewModel : ViewModelBase
{
    private bool _threadStopped;
    private RelayCommand _executeCommand;
    private string _output;
    private Dispatcher _currentDispatcher;
    public WindowViewModel()
    {
        _threadStopped = true;
        _currentDispatcher = Dispatcher.CurrentDispatcher;
    }

    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;
        }
    }

    private delegate void ZeroArgDelegate();

    public bool CanExecuteThread
    {
        get
        {
            return _threadStopped;
        }
    }

    private void ExecuteThread(object p)
    {
        ThreadStart ts = new ThreadStart(ThreadMethod);
        Thread t = new Thread(ts);
        t.Start();
    }

    private void ThreadMethod()
    {
        _threadStopped = 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);
        }
        _threadStopped = true;
        _currentDispatcher.BeginInvoke(new ZeroArgDelegate(resetButtonState), null);
        Output += "Thread Stopped:  Is the 'Execute' button enabled?\r\n";
    }

    private void resetButtonState()
    {
        CommandManager.InvalidateRequerySuggested();
    }
}
于 2010-08-02T20:56:01.930 に答える