开发者

WPF: Binding Combobox in Code Behind to Property

开发者 https://www.devze.com 2022-12-23 18:29 出处:网络
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:

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"),
    Mod开发者_高级运维e = 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消