在你的例子做的最簡單的辦法是使用ObservableCollection<string>
(在System.Collections.ObjectModel命名空間),而不是一個列表。 ObservableCollection <>會在項目添加/刪除到集合時通知您的列表框,並且您的UI將通過WPF數據綁定的魔術更新。當你的用戶界面在集合更改時會更新(新項目將出現在列表框中,並且刪除的項目將從列表框中刪除),這會讓你獲得一半的位置。
ObservableCollection<string> Lista_punto_intermedio = new ObservableCollection<string>();
然後,你可能希望你的列表框更新時的一個字符串隨之改變(例如:如果「測試......」被更新爲「工作...」,你可能希望你的列表框中顯示「正在......」)。爲了使用WPF數據綁定,您需要在ObservableCollection中的對象上實現IPropertyNotifyChanged。爲此,您可以爲文本引入一個帶有字符串屬性的新類。也許是這樣的:
public class MyNotifyableText : INotifyPropertyChanged
{
private string _myText;
public string MyText {
get { return this._myText; }
set
{
if(this._myText!= value)
{
this._myText= value;
this.NotifyPropertyChanged("MyText");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName)
{
if(this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
當「MYTEXT」屬性改變,這將使你的列表框進行相應的更新此對象將發送通知到WPF數據綁定。爲了配合這一新的對象和你的列表框在一起,你將不得不改變你的XAML因此列表框會顯示您的「MYTEXT」屬性,改變ObservableCollection<string>
是ObservableCollection<MyNotifyableText>
這裏有一個最終的代碼示例:
XAML(注該屬性的DisplayMemberPath):
<ListBox Name="ListBox_PuntosIntermedios" DisplayMemberPath="MyText" MaxHeight="80" Height="80" ScrollViewer.VerticalScrollBarVisibility="Auto" >
</ListBox>
項目清單:
ObservableCollection<MyNotifyableText> Lista_punto_intermedio = new ObservableCollection<MyNotifyableText>();
負載:
Lista_punto_intermedio.Add(new MyNotifyableText(){ MyText="testing..." });
ListBox_PuntosIntermedios.ItemsSource = Lista_punto_intermedio;
最後,我發現這個教程有幫助的學習WPF數據綁定:http://www.wpf-tutorial.com/data-binding/responding-to-changes/
做快速在下面的谷歌搜索有很多的例子有 'C#stackoverflow綁定列表框與列表' –
MethodMan
做到了這一點,但這些例子對我來說還不夠清楚。 –
這些例子非常簡單,甚至不好笑 – MethodMan