简体   繁体   中英

WPF: Binding Combobox in Code Behind to Property

This might be something very straight forward and I really think it should work as is, but it doesn't... I have the following scenario:

var itemSource = new Binding
{
    Path = new PropertyPath("ItemList"),
    Mode = BindingMode.OneTime
};       

comboBox.SetBinding(ItemsControl.ItemsSourceProperty, itemSource);

ItemList is simply:

public IList<string> ItemList
{
   get
   {
        return Enum.GetNames(typeof(OptionsEnum)).ToList();
   }
}

I would have expected this to bind the list of items to the Combobox, and when I do it in XAML it works fine, but I have to do it in code behind...

Any ideas?

I took the following comment as my answer:

I'd create a property in the view model that checked the setting and exposed the appropriate list rather than screwing around with code-behind. It's much easier to test. – Robert Rossney

Have you set the Combobox's DataContext to the ItemList 's parent object? So comboBox.DataContext = MyObj; where MyObj has the ItemList property on it.

Check again thet the DataContext is set to the object that have the ItemList property. A very good way see what is the real DataContext is to use Snoop . There is no problem with your code, Jast the DataContext .

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