Abhishek
Abhishek

Reputation: 2945

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

I have two TextBoxes. I have two ObservableCollections. 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 ObservableCollections. The ObservableCollections 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

Upvotes: 0

Views: 892

Answers (1)

RoelF
RoelF

Reputation: 7573

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}" />

Upvotes: 1

Related Questions