简体   繁体   中英

wpf programatically set combobox selected item when bound to dictionary

I have a combobox which is bound do a dictionary

Dictionary<String, myClass> boxItems;

The combobox has the following dataTemplate:

<DataTemplate>
    <TextBlock Text="{Binding Path=Key}"></TextBlock>
</DataTemplate>

This works fine for loading the values and getting the selected value, however I can't figure out how to set the selected value from codebehind.

any pointers?

I've tried setting selectedItem and selectedValue to a Key (which I know is in the dictionary), but when I load the page, the combobox hasn't selected anything.

Add this to your ComboBox

<ComboBox SelectedItem="{Binding SelectedBoxItem}"/>

And use this in a class that implements INotifyPropertyChanged:

private myClass _selectedBoxItem;
public myClass SelectedBoxItem
{
    get { return _selectedBoxItem; }
    set
    {
        _selectedBoxItem = value;
        OnPropertyChanged("SelectedBoxItem");
    }
}

You need to create a KeyValuePair with the key you want to select.

You can do something like this:

 myCombo.SelectedItem = new KeyValuePair<string, int>("myKey", boxItems["myKey"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM