繁体   English   中英

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

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

我有两个TextBox 我有两个ObservableCollection 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));
        }
    }
}

我需要将每个TextBox.Text绑定到每个ObservableCollection的Value属性。 ObservableCollection也是窗口中其他控件的DataContext 由于我有多个ObservableCollection ,因此无法将DataContext设置为Window。

使用以下命令将新数据添加到ObservableCollection中:

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

当将新值添加到集合时,我希望TextBox显示Value属性

如果您不需要“真实”绑定,而只需显示最后添加的对象的值(伪代码),则可以尝试这样的操作:

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