Mert Can Ergün
Mert Can Ergün

Reputation: 399

Binding to an array's element changing with combobox index

class DAC : INotifyPropertyChanged
{
    private uint _value;
    private bool _isCurrent;
    private string _name;
    private uint _address;
    private bool _powerDown;
    private bool _lowPower;
    private bool _enable;

    public bool Enable
    {
        get { return _enable; }
        set 
        {
            if (_enable == value)
            {
                return;
            }
            _enable = value;
            OnPropertyChanged("Enable");
        }
    }

    //The rest of the property definitions looks like the first one

    public uint Value
    {
        get { return _value; }
        set 
        {
            if (_value == value)
            {
                return;
            }
            _value = value;
            OnPropertyChanged("Value");
        }
    }

    #region INotifyProperty Definitions
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    } 
    #endregion
}

So this is my basic class, which I aim to use for populating a list. I basically have an array of DACs (or some other derivative of DAC) that I list on a combobox. The combobox populates itself with

combobox1.SetBinding(ComboBox.ItemsSourceProperty, new Binding() { Source = cdacList });
combobox1.DisplayMemberPath = "Name";

When user chooses one of the items in there, it is supposed to update a textbox's and a slider's values according to the index selected from combobox and use that index to access data from an array.

I tried directly binding with

textbox1.SetBinding(TextBox.TextProperty, new Binding("Address") { Source = cdacList[combobox1.SelectedIndex] });
slider1.SetBinding(Slider.ValueProperty, new Binding("Value") { Source = cdacList[combobox1.SelectedIndex] });

But it doesn't update itself. I know I need to get some other aspect to do this with binding but I just cant figure it out myself.

Upvotes: 0

Views: 792

Answers (1)

Clemens
Clemens

Reputation: 128077

You should be able to set the bindings once like shown below, without a need to change them later:

textbox1.SetBinding(TextBox.TextProperty,
    new Binding("SelectedItem.Address") { Source = combobox1 });
slider1.SetBinding(Slider.ValueProperty,
    new Binding("SelectedItem.Value") { Source = combobox1 });

That said, the bindings should be created in XAML:

<TextBox x:Name="textbox1"
    Text="{Binding SelectedItem.Address, ElementName=combobox1}" .../>
<Sliderx:Name="slider1"
    Text="{Binding SelectedItem.Value, ElementName=combobox1}" .../>

Upvotes: 1

Related Questions