WPF ComboBox Does NOT Have a Right Item Selected When Initialized

Published on Saturday, May 11, 2019

WPF ComboBox Does NOT Have a Right Item Selected When Initialized

Sometimes even we set all done (Set data binding correctly) for a ComboBox for in WPF, but the ComboBox can not still show current item but just an empty selection.

For this issue, we can use a separate thread to set the current item ID.

public class MyItem : baseClass
{
    private int _myID;
    public int MyID
    {
        get { return _myID; }
        set
        {
            _myID = value;
            NotifyPropertyChanged("MyID");
        }
    }

    private string _myName;
    public string MyName
    {
        get { return _myName; }
        set
        {
            if (_myName != value)
            {
                _myName = value;
                NotifyPropertyChanged("MyName");
            }
        }
    }
}

...
...

public class MyElement : VMBase
{
    private int _id;
    public int ID
    {
        get { return _id; }
        set
        {
            if (value != _id)
            {
                _id = value;
                NotifyPropertyChanged("ID");
            }
        }
    }

    private string _name;
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            if (value != _name)
            {
                _name = value;
                NotifyPropertyChanged("Name");
            }
        }
    }
}

...
public ObservableCollection<MyElement> MyElementList { get; set; }

...
...

//Xaml
<ComboBox Height="23" Width="225" SelectionChanged="cboTrippedElement_SelectionChanged" Cursor="Hand"  Margin="0,0,5,0" 
    ItemsSource="{Binding MyElementList}" DisplayMemberPath="Name" SelectedValuePath ="ID"  SelectedValue="{Binding Path=MyID}"  />
...

Sometimes the ComboBox above does not work correctly - no a pre-selected item but just leave empty

There is a solution here:

When get data, use a seperate thread to set the ID:


//this will happen in interrupting device ComboBox and in Edit mode, if use selects an item from another Contingency list, existing interruput
//device might be the same, if no a dispatcher event is launched, the combox will not a pre-selected item but show an empty selection 

System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => this.MyID = this.MyID),
           System.Windows.Threading.DispatcherPriority.ApplicationIdle);