This question looks like this one :
Programmatically binding List to ListBox
but as far as my example is concerned, the answers given in this post doesn’t work for me !
Anyway, I looked at about 10/15 similar posts but none worked
Here is my xaml code :
<Grid>
<ListBox Name="ListBoxx"/>
</Grid>
And here is the code behind :
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ObservableCollection<string> MyCollection = new ObservableCollection<string>();
Random random = new Random();
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += (sender, e) =>
{
MyCollection.Add(random.Next(0, 100).ToString());
};
aTimer.Interval = 500;
aTimer.Enabled = true;
Binding myBinding2 = new Binding();
myBinding2.Source = this;
myBinding2.Path = new PropertyPath("MyCollection");
ListBoxx.SetBinding(ListBox.ItemsSourceProperty, myBinding);
}
}
}
As far as I know, my class doesn’t have to inherit from INotifyPropertyChanged cause I use an ObservableCollection.
I don’t wanna use a {Binding} in xaml code.
I tried this code :
ListBoxx.ItemsSource = MyCollection;
this “works” but I got a thread crash. I know I can use Dispatcher to fix it but it doesn’t fix with my code. I wanna use a “real” binding (configurable) like in my code snippet.
The result is that I got no error but the ListBox just doesn’t update :/
I tried to add the lines :
MyCollection.Add("aaa");
MyCollection.Add("bbb");
MyCollection.Add("ccc");
MyCollection.Add("ddd");
but I don’t get anything in my application so I really think this is a binding problem. Anyway, I’m SURE that my Timer is OK, The problem’s not here.
I tried too to get MyCollection as Property like this :
private ObservableCollection<string> _MyCollection = new ObservableCollection<string>();
public ObservableCollection<string> MyCollection { get { return _MyCollection; } }
but it doesn’t work too :/ (no error but no update)
The code you posted is going to fail because “MyCollection” isn’t a property in MainWindow. Your Visual Studio output window is probably showing binding errors.
Additionally you indeed need to dispatch the changes you make to the collection, you can use a DispatcherTimer to do this. There should be errors in the output window about that too.
The code below works: