绑定到使用组合框索引更改的数组元素

时间:2015-04-12 12:45:28

标签: c# wpf indexing data-binding combobox

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
}

所以这是我的基础课程,我的目的是用来填充列表。我基本上有一组DAC(或DAC的其他衍生物),我在组合框中列出。 组合框填充

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

当用户选择其中一个项目时,应根据从组合框中选择的索引更新文本框和滑块的值,并使用该索引访问数组中的数据。

我尝试直接绑定

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

但它不会自我更新。我知道我需要通过绑定来获得其他方面,但我不能自己解决这个问题。

1 个答案:

答案 0 :(得分:0)

您应该能够设置一次如下所示的绑定,而无需在以后更改它们:

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

也就是说,绑定应该在XAML中创建:

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