我正在尝试在 WP7 项目中使用性能进度条,但我在异步 webclient 调用时遇到了问题。我的代码如下:
更新
public MainPage()
{
InitializeComponent();
...................
this.Loaded += new RoutedEventHandler(MainPage_Loaded);}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
以及我实现 LoadData 函数的 ViewModel
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)
{.....
}
主页 Xaml
<toolkit:PerformanceProgressBar Margin="0,-12,0,0" x:Name="performanceProgressBar" IsIndeterminate="true" Visibility="{Binding ShowProgressBar, Converter={StaticResource BooleanToVisibilityConverter}}"/>
我的问题是因为 WebClient 在执行时是一个异步方法,所以 LoadData 已经执行了,我不知道在哪里放置 performanceProgressBar.Visibility
任何帮助,将不胜感激。谢谢!