简体   繁体   中英

Binding TextBox.Text to a Property in a class in ObservableCollection

I have two TextBox es. I have two ObservableCollection s. The ObservableCollection has items of the following type:

public class ChartData : INotifyPropertyChanged
{
    DateTime _Name;
    double _Value;

    #region properties

    public DateTime Name
    {
        get
        {
            return _Name;
        }
        set
        {
            _Name = value;
            OnPropertyChanged("Name");
        }
    }

    public double Value
    {
        get
        {
            return _Value;
        }
        set
        {
            _Value = value;
            OnPropertyChanged("Value");
        }
    }

    #endregion

    public event PropertyChangedEventHandler PropertyChanged;

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

I need to bind each of the TextBox.Text to the Value Property in each of the ObservableCollection s. The ObservableCollection s are DataContext for other controls in the window too. Since I have more than one ObservableCollection , I cannot set the DataContext to the Window.

New data is added to the ObservableCollection using:

ObservableCollection<ChartData>lineSeries1Data = new ObservableCollection<ChartData>();
lineSeries1Data.Add(new ChartData() { Name = DateTime.Now, Value = 0.0 });

When a new Value is added to the Collection, I want the TextBox to show the Value property

You can try something like this if you don't need a "real" binding, but just need to display the Value of the last object which is added (pseudo code):

public string NewItem { get; set+notify; }

ctor(){
    myCollection = new ObservableCollection<T>();
    myCollection.CollectionChanged += OnMyCollectionChanged;
}

private void OnMyCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
    if (args.Action == NotifyCollectionChangedAction.Add){
        var last = args.NewItems.FirstOrDefault();
        if (last == null) return;
        NewItem = last.Value;
    }
}


//XAML:
<TextBox Text="{Binding NewItem, Mode=OneWay}" />

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