Reset combobox selected item on set using MVVM

丶灬走出姿态 提交于 2019-11-27 15:10:01

This is a very interesting question. First I agree with other guys that this is a not recommended approach to handle invalid selection. As @blindmeis suggests, IDataErrorInfo is one of good way to solve it.

Back to the question itself. A solution satisfying what @Faisal Hafeez wants is:

public string SelectedItem
{
    get { return _selectedItem; }
    set
    {
        var oldItem=_selectedItem;
        _selectedItem=value;
        OnPropertyChanged("SelectedItem")

        if (!SomeCondition(value)) //If does not satisfy condition, set item back to old item
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => SelectedItem = oldItem),
                                                 DispatcherPriority.ApplicationIdle);
    }
}

Dispatcher is an elegant way to handle some UI synchronization during another UI sync. For example in this case, you want to reset selection during a selection binding.

A question here is why we have to update selection anyway at first. That's because SelectedItem and SelectedValue are separately assigned and what display on ComboBox does not depend on SelectedItem (maybe SelectedValue, I am not sure here). And another interesting point is if SelectedValue changes, SelectedItem must change but SelectedItem does not update SelectedValue when it changes. Therefore, you can choose to bind to SelectedValue so that you do not have to assign first.

Try changing the XAML to this

<ComboBox ItemsSource="{Binding ItemsCollection}" SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<ComboBox ItemsSource="{Binding ItemsCollection}" SelectedIndex="{Binding currSelection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged} " />

And in your VM

{
    set{ 
        currSelection = -1;
    }
}

If you are looking for a MVVM / XAML re-usable solution, I put this together for another thread. This uses a WPF Behavior and is very simple to manage. No external libs. Copy in solution.

ComboBox Selected Item Clear Behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!