I am populating the list view items dynamically. At the same time I wanna display a progress bar. When data populated the progress bar should be disabled. How to achieve thi
I prefer to control view state via presentation model. When view needs to populate items in address to presentation model that starts Worker thread and updates its progress values on UI synchronization context.
public class SampleModel : ObservableObject
{
private ObservableCollection _items = new ObservableCollection();
public IEnumerable Items
{
get
{
return this._items;
}
}
private int _progress;
public int Progress
{
get
{
return this._progress;
}
set
{
if (this._progress != value)
{
this._progress = value;
this.OnPropertyChanged("Progress");
}
}
}
public void Fill()
{
this.Progress = 0;
var sc = SynchronizationContext.Current;
new Thread(new ThreadStart(() =>
{
for (int i = 0; i < 100; i++)
{
sc.Post(p =>
{
this._items.Add(i.ToString());
this.Progress ++;
}, null);
Thread.Sleep(100);
}
sc.Post(p =>
{
this.Progress = 0;
}, null);
}))
.Start();
}
}
XAML:
And code behind:
public MainWindow()
{
InitializeComponent();
this.Model = new SampleModel();
this.Start.Click += new RoutedEventHandler(Start_Click);
}
void Start_Click(object sender, RoutedEventArgs e)
{
this.Model.Fill();
}
protected SampleModel Model
{
get
{
return (SampleModel)this.DataContext;
}
set
{
this.DataContext = value;
}
}