Tiho
Tiho

Reputation: 123

combobox binding

Please can you tell me how can I bind combobox.

I had combobox which Itemsource is ObservableCollection<strings>. I wont to set Selected Combobox value to MainObject.SomeValue and vice versa.

Which is the easiest way

Upvotes: 0

Views: 817

Answers (1)

TerenceJackson
TerenceJackson

Reputation: 1786

here's a little example. I have two classes:

 public class Person
    {
        private string _name = "Test2";
        public String Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }

    public class DataProvider
    {
        public ObservableCollection<String> Data { get; set; }

        public DataProvider()
        {
            Data = new ObservableCollection<string>();
            Data.Add("Test");
            Data.Add("Test2");
            Data.Add("Test3");
            Data.Add("Test4");
        }
    }

The DataProvider provides the string data for the combo box and the Person is the object where you want to bind the name. This can be done as followed:

<Grid.Resources>
            <myNamespace:DataProvider x:Key="DataProvider"/>
            <myNamespace:Person x:Key="Person"/>
        </Grid.Resources>
        <ComboBox 
            Height="25" 
            DataContext="{StaticResource DataProvider}" 
            ItemsSource="{Binding Data}" 
            SelectedItem="{Binding Name, Source={StaticResource Person}, Mode=TwoWay}"/>

This is just a quick example. Have a look at SelectedItem, SelectedValue, SelectedValuePath if you don't want to use string as input data...

Is this what you needed?

BR,

TJ

Upvotes: 1

Related Questions