I am trying to use performance progressbar in a WP7 project but I have trouble with the async webclient call. My code is as follows:
Update
public MainPage()
{
InitializeComponent();
...................
this.Loaded += new RoutedEventHandler(MainPage_Loaded);}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
And the ViewModel where I implement the LoadData function
private bool _showProgressBar = false;
public bool ShowProgressBar
{
get { return _showProgressBar; }
set
{
if (_showProgressBar != value)
{
_showProgressBar = value;
NotifyPropertyChanged("ShowProgressBar");
}
}
public void LoadData()
{
try
{
string defaulturl = "http://....";
WebClient client = new WebClient();
Uri uri = new Uri(defaulturl);
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
ShowProgressBar = true;
client.DownloadStringAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
this.IsDataLoaded = true;
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
//fetch the data
ShowProgressBar = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{.....
}
MainPage Xaml
<toolkit:PerformanceProgressBar Margin="0,-12,0,0" x:Name="performanceProgressBar" IsIndeterminate="true" Visibility="{Binding ShowProgressBar, Converter={StaticResource BooleanToVisibilityConverter}}"/>
My problem is that because the WebClient is an async method when it is executed, the LoadData has already been executed and I can’t figure out where to place the performanceProgressBar.Visibility
Any help would be appreciated. Thanks!
After you explained more in your comments, I understand more. Sounds like you want to bind a boolean property to the visibility of your progress bar. You’ll need a boolean-to-visbility converter (google it, it’s easy to find).
Then you can do something like this:
On the View:
Apparently, MSFT offers a converter for you already…this is news to me: http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter.aspx