简体   繁体   中英

C# WPF MVVM ComboBox Binding

First of all, what I'm trying to do is a "simple" binding of a ComboBox to my source.

The structure is something like:

public class Data
{
    public ObservableList<string> List {get;set;}
    public string Selected {get;set;}
}

Also, it implements INotifyPropertyChanged interface. My problem is, i found several solutions to do this via XAML, unfortunately i can't do it with XAML since my ComboBoxes have to be generated during runtime.

So my question is, how i can bind my ComboBox to Data.List , and also the selected item (value?) to Data.Selected, and this one should be TwoWay so my Data class knows that something was selected. Keep in mind this has to be through c# code (XAML is no option unfortunately).

Thanks in advance. :)

It's pretty easy. Assuming, that Data has properties instead of fields:

public class Data
{
    public Data()
    {
        List = new ObservableCollection<string>
        {
            "Apple", "Orange", "Lime"
        };
    }

    public ObservableCollection<string> List { get; private set; }
    public string Selected { get; set; }
}

you can write this:

var comboBox = new ComboBox
{
    DataContext = new Data()
};

comboBox.SetBinding(ComboBox.ItemsSourceProperty, new Binding("List"));
comboBox.SetBinding(ComboBox.SelectedItemProperty, new Binding("Selected") 
{ 
    Mode = BindingMode.TwoWay
});

To add ComboBox into visual tree, just call proper method for the container. Eg, this will work with any ContentControl (like Window ):

AddChild(comboBox);

how i can bind my combobox to Data.List, and also the selected item (value?)

Create a custom composite user control which contains the combobox. Map the combobox's properties to two dependencies properties created on the custom control, one to load the data and the other to provide an on demand selected item's data. Any plumbing needs are done inside the codebehind which ultimately provides all the magic.

Then you can create/bind this control dynamically in codebehind as needed in the other page you are working on.

Sounds like a sort of "recursive binding". If your combos are in a container control, what you need is bound the container to a collection of your single combo model, so each view in the ItemsControl will be bound to a single combo model.

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