简体   繁体   English

将TextBox.Text绑定到ObservableCollection中的类中的属性

[英]Binding TextBox.Text to a Property in a class in ObservableCollection

I have two TextBox es. 我有两个TextBox I have two ObservableCollection s. 我有两个ObservableCollection The ObservableCollection has items of the following type: ObservableCollection具有以下类型的项:

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. 我需要将每个TextBox.Text绑定到每个ObservableCollection的Value属性。 The ObservableCollection s are DataContext for other controls in the window too. ObservableCollection也是窗口中其他控件的DataContext Since I have more than one ObservableCollection , I cannot set the DataContext to the Window. 由于我有多个ObservableCollection ,因此无法将DataContext设置为Window。

New data is added to the ObservableCollection using: 使用以下命令将新数据添加到ObservableCollection中:

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 当将新值添加到集合时,我希望TextBox显示Value属性

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM