Deep Panda
Deep Panda

Reputation: 86

Binding WPF combobox with changed collection

I have a combobox inside a list where the items of the combo box are dynamic. They will be determined by the help of the selected item.

For example: If selected item is Item1 then combobox should contain Item1, Item2, Item3 but if selected item is Item2 then combo box should contain Item2, Item3, Item4

How to achieve the same by using binding..

Right now i am setting up two properties in my collection called SelectedValue and ListValues and binding them with my combobox but it only select first item of the list and leaving the rest one as it is.

Also, what is the order of execution of data binding as i want first Itemsource to call then selectedvalue should be set so that items will be selected.

Really appreciate for any help.

Here is my effort which works out but i am not sure if it's correct or not.

C#

public string SelectedValue
{
    get
    {
        PropertyChanged.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs("Values"));
        return _value;
    }
    set
    {
        if (value != null) //It will be null when binding of values happens
        { 
            _value = value;
            PropertyChanged.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs("Values"));
            PropertyChanged.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs("SelectedValue"));
        }
    }
}

public IList<SomeType> Values
{
    get
    {
        string status =_status;
        return SomeFunctionToReturnValues(status);
    }
}

XAML

<ComboBox SelectedValue="{Binding SelectedValue}" SelectedValuePath="Id" DisplayMemberPath="Text" Width="120" ItemsSource="{Binding Values,Mode=OneWay}"></ComboBox>

Please comment and Let me know if anyone can provide me better suggestion here.

Upvotes: 2

Views: 1666

Answers (1)

Noam M
Noam M

Reputation: 3164

You shold use ItemsSource property

<ComboBox SelectedItem="{Binding MyNum}" ItemsSource="{Binding Numbers}" Width="100" Height="30"/>

That bound to:

// Fills up combo box
public IEnumerable<int> Numbers
{
    get
    {
        IEnumerable<int> temp = MyCollection.ToList(); 
        return temp.SubArray(MyNum,MyCollection.count);
    }
}

private int _myNum
public int MyNum
{
    get
    {
        return  _myNum;
    }
    set
    {
        _myNum = value;
        OnPropertyChanged("MyNum");
    }
}

When the SubArray is (Credit)

public static T[] SubArray<T>(this T[] data, int index, int length)
{
    T[] result = new T[length];
    Array.Copy(data, index, result, 0, length);
    return result;
}

Upvotes: 1

Related Questions