22

SelectedItemがViewModelにバインドされているComboBoxがあります。

<ComboBox SelectedItem="{Binding SelItem, Mode=TwoWay}" ItemsSource="{Binding MyItems}">

ユーザーがViewComboBoxで新しいアイテムを選択したときに、プロンプトを表示して、変更を加えることを確認したいと思います。

ビューモデルのSetItemプロパティセッターで、選択を確認するためのダイアログを表示します。彼らがイエスと言うとき、それはうまくいきます。

私の問題は、ユーザーが「いいえ」をクリックしたときに、ComboBoxを以前の値に戻すために誰を取得するかわからないことです。ViewModelのプロパティには正しい古い値がありますが、ViewではComboBoxに新しく選択された値が表示されます。

ユーザーにアイテムを選択して、続行することを確認してもらいます。選択しない場合は、ComboBoxを前のアイテムに戻します。

どうすればこれを達成できますか?ありがとう!

4

4 に答える 4

26

ユーザーが「いいえ」と言った場合、WPF は値が変更されたことを認識しません。WPFに関する限り、値はユーザーが選択したものです。

プロパティの変更通知を発行してみてください。

public object SelItem
{
    get { ... }
    set
    {
        if (!CancelChange())
        {
            this.selItem = value;
        }

        OnPropertyChanged("SelItem");
    }
}

問題は、選択イベントの同じコンテキスト内で変更通知が発生することです。したがって、プロパティが変更されたことを既に認識しているため、WPF はそれを無視します (ユーザーが選択した項目に変更されました)。

あなたがする必要があるのは、別のメッセージで通知イベントを発生させることです:

public object SelItem
{
    get { ... }
    set
    {
        if (CancelChange())
        {
            Dispatcher.BeginInvoke((ThreadStart)delegate
            {
                OnPropertyChanged("SelItem");
            });
            return;
        }

        this.selItem = value;
        OnPropertyChanged("SelItem");
    }
}

WPF は、selection changed イベントの処理が完了した後にこのメッセージを処理するため、ビューの値をあるべき値に戻します。

VM は明らかに現在の にアクセスする必要がありますDispatcher。これを行う方法についての指針が必要な場合は、ベース VM クラスに関する私のブログ投稿を参照してください。

于 2010-04-06T13:56:09.843 に答える
14

この質問と回答をありがとう。Dispatcher.BeginInvoke は私を助け、私の最終的な解決策の一部でしたが、上記の解決策は私の WPF 4 アプリではうまくいきませんでした。

その理由を理解するために、小さなサンプルをまとめました。基礎となるメンバー変数の値を実際に一時的に変更するコードを追加して、WPF がゲッターを再クエリしたときに値が変更されたことを確認できるようにする必要がありました。そうしないと、UI はキャンセルを適切に反映せず、BeginInvoke() 呼び出しは何もしませんでした。

これは、機能しない実装と機能する実装を示す私のサンプルを含む私のブログ投稿です。

私のセッターは次のようになりました:

    private Person _CurrentPersonCancellable;
    public Person CurrentPersonCancellable
    {
        get
        {
            Debug.WriteLine("Getting CurrentPersonCancellable.");
            return _CurrentPersonCancellable;
        }
        set
        {
            // Store the current value so that we can 
            // change it back if needed.
            var origValue = _CurrentPersonCancellable;

            // If the value hasn't changed, don't do anything.
            if (value == _CurrentPersonCancellable)
                return;

            // Note that we actually change the value for now.
            // This is necessary because WPF seems to query the 
            //  value after the change. The combo box
            // likes to know that the value did change.
            _CurrentPersonCancellable = value;

            if (
                MessageBox.Show(
                    "Allow change of selected item?", 
                    "Continue", 
                    MessageBoxButton.YesNo
                ) != MessageBoxResult.Yes
            )
            {
                Debug.WriteLine("Selection Cancelled.");

                // change the value back, but do so after the 
                // UI has finished it's current context operation.
                Application.Current.Dispatcher.BeginInvoke(
                        new Action(() =>
                        {
                            Debug.WriteLine(
                                "Dispatcher BeginInvoke " + 
                                "Setting CurrentPersonCancellable."
                            );

                            // Do this against the underlying value so 
                            //  that we don't invoke the cancellation question again.
                            _CurrentPersonCancellable = origValue;
                            OnPropertyChanged("CurrentPersonCancellable");
                        }),
                        DispatcherPriority.ContextIdle,
                        null
                    );

                // Exit early. 
                return;
            }

            // Normal path. Selection applied. 
            // Raise PropertyChanged on the field.
            Debug.WriteLine("Selection applied.");
            OnPropertyChanged("CurrentPersonCancellable");
        }
    }
于 2010-04-25T20:57:16.303 に答える
1

それを行う別の方法(コメントも必ず読んでください):

http://amazedsaint.blogspot.com/2008/06/wpf-combo-box-cancelling-selection.html

リンクから:グローバル変数なしでイベントハンドラーを再帰的に呼び出す問題の別の解決策は、プログラムによる選択の変更の前にハンドラーの割り当てをキャンセルし、その後に再割り当てすることです。

元:

cmb.SelectionChanged -= ComboBox_SelectionChanged;
cmb.SelectedValue = oldSel.Key;
cmb.SelectionChanged += ComboBox_SelectionChanged;
于 2010-04-06T14:01:33.840 に答える
1

私のやり方は、変更を通過させ、Dispatcher で BeginInvoked であるラムダで検証を実行することです。

    public ObservableCollection<string> Items { get; set; }
    private string _selectedItem;
    private string _oldSelectedItem;
    public string SelectedItem
    {
        get { return _selectedItem; }
        set {
            _oldSelectedItem = _selectedItem;
            _selectedItem = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem"));
            }
            Dispatcher.BeginInvoke(new Action(Validate));                
        }
    }

    private void Validate()
    {            
        if (SelectedItem == "Item 5")
        {
            if (MessageBox.Show("Keep 5?", "Title", MessageBoxButton.YesNo) == MessageBoxResult.No)
            {
                SelectedItem = _oldSelectedItem;
            }
        }
    }

またはあなたのViewModelで:

   Synchronization.Current.Post(new SendOrPostCallback(Validate), null);
于 2014-10-03T12:41:39.127 に答える