WPF: Cancel a user selection in a databound ListBox?

前端 未结 8 789
独厮守ぢ
独厮守ぢ 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条回答
  •  没有蜡笔的小新
    2020-12-05 01:11

    Got it! I am going to accept majocha's answer, because his comment underneath his answer led me to the solution.

    Here is wnat I did: I created a SelectionChanged event handler for the ListBox in code-behind. Yes, it's ugly, but it works. The code-behind also contains a module-level variable, m_OldSelectedIndex, which is initialized to -1. The SelectionChanged handler calls the ViewModel's Validate() method and gets a boolean back indicating whether the Document is valid. If the Document is valid, the handler sets m_OldSelectedIndex to the current ListBox.SelectedIndex and exits. If the document is invalid, the handler resets ListBox.SelectedIndex to m_OldSelectedIndex. Here is the code for the event handler:

    private void OnSearchResultsBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var viewModel = (MainViewModel) this.DataContext;
        if (viewModel.Validate() == null)
        {
            m_OldSelectedIndex = SearchResultsBox.SelectedIndex;
        }
        else
        {
            SearchResultsBox.SelectedIndex = m_OldSelectedIndex;
        }
    }
    

    Note that there is a trick to this solution: You have to use the SelectedIndex property; it doesn't work with the SelectedItem property.

    Thanks for your help majocha, and hopefully this will help somebody else down the road. Like me, six months from now, when I have forgotten this solution...

提交回复
热议问题