[英]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.