WPF: Cancel a user selection in a databound ListBox?

前端 未结 8 778
独厮守ぢ
独厮守ぢ 2020-12-05 01:02

How do I cancel a user selection in a databound WPF ListBox? The source property is set correctly, but the ListBox selection is out of sync.

I have an MVVM app that

8条回答
  •  Happy的楠姐
    2020-12-05 01:14

    -snip-

    Well forget what I wrote above.

    I just did an experiment, and indeed SelectedItem goes out of sync whenever you do anything more fancy in the setter. I guess you need to wait for the setter to return, and then change the property back in your ViewModel asynchronously.

    Quick and dirty working solution (tested in my simple project) using MVVM Light helpers: In your setter, to revert to previous value of CurrentDocument

                    var dp = DispatcherHelper.UIDispatcher;
                    if (dp != null)
                        dp.BeginInvoke(
                        (new Action(() => {
                            currentDocument = previousDocument;
                            RaisePropertyChanged("CurrentDocument");
                        })), DispatcherPriority.ContextIdle);
    

    it basically queues the property change on the UI thread, ContextIdle priority will ensure it will wait for UI to be in consistent state. it Appears you cannot freely change dependency properties while inside event handlers in WPF.

    Unfortunately it creates coupling between your view model and your view and it's an ugly hack.

    To make DispatcherHelper.UIDispatcher work you need to do DispatcherHelper.Initialize() first.

提交回复
热议问题