我在 winform 中托管了 WPF 控件,其中包含菜单和一些标签。WPF 控件连接到 Internet 以下载一些数据。我将代码分为两个步骤,首先设置控件属性,第二个连接到网络,第二个在线程内运行,但是在 WPF 控件完成他的两个步骤之前,Winform 控件不会在窗体上发生。
我已经尝试了许多方法来使其具有线程能力,但所有方法都指向同一个目的地。
代码 1- 加载 WPF 控件
private void MDI_Load(object sender, EventArgs e)
{
MenuManager.FillMenu(MainMenu); // I have filled WinForm Menu first, but it doesn't appear until WPF finish
#region = WPF Control =
wpfManager.AddweatherControl();
wpfManager.weatherManager.Start(); // This have to run in another thread
#endregion
}
2- wpfManager.weatherManager.Start
public void Start()
{
//var tsk = System.Threading.Tasks.Task.Factory.StartNew(GetWeather);
//tsk.ContinueWith(t => { MessageBox.Show(t.Exception.InnerException.Message); },
// System.Threading.CancellationToken.None, System.Threading.Tasks.TaskContinuationOptions.OnlyOnFaulted,
// System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());
//System.Threading.Thread t = new System.Threading.Thread(
// () => weatherControl.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(GetWeather))
// );
//t.SetApartmentState(System.Threading.ApartmentState.STA);
//t.Start();
weatherControl.Dispatcher.BeginInvoke(new Action(GetWeather), new object[] { });
}
void GetWeather()
{
#region = Weather =
Yweather.Getweather(UserManager.CurrentUser.Preferences.WeatherCity);
if (Yweather.Online && Yweather.IDayForecast.Count > 0)
{
weatherControl.CurrentDegree.Text = Yweather.IDayForecast[0].CurrentTemperature.ToString();
weatherControl.WeatherTypeName.Text = Yweather.IDayForecast[1].WeatherText;
weatherControl.AllDayDegree.Text = Yweather.IDayForecast[1].LowTemperature + " - " + Yweather.IDayForecast[1].HighTemperature;
weatherControl.WeatherType.Source = wpfManager.BitmapToImageSource(Yweather.IDayForecast[0].Image);
xWeatherDay weatherday1 = weatherControl.OhterDaysPanel.Children[0] as xWeatherDay;
weatherday1.AllDayDegree.Text = Yweather.IDayForecast[2].LowTemperature + " - " + Yweather.IDayForecast[2].HighTemperature;
weatherday1.WeatherType.Source = wpfManager.BitmapToImageSource(Yweather.IDayForecast[2].Image);
}
else
{
weatherControl.CurrentDegree.Text = "0";
weatherControl.WeatherTypeName.Text = "NAN";
weatherControl.AllDayDegree.Text = "0 - 0";
weatherControl.WeatherType.Source = wpfManager.BitmapToImageSource(Yweather.OfflineImage);
}
#endregion
}