1.在Worker thread 中更新 UI
WebRequest 对象去向某个页面 Post 一些内容更新UI,直接更新是不行的,
原因是因为silvelight调用的服务全都是异步。
如下面的代码:
代码
void ResponseReady(IAsyncResult asyncResult)
{
WebRequest request = asyncResult.AsyncState as WebRequest;
WebResponse response = request.EndGetResponse(asyncResult);
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
//this.lbPrice.Text = "价格:" + reader.ReadToEnd();
//在异步更新UI可以这样使用
lbPrice.Dispatcher.BeginInvoke(new UpdatePriceDelegate(UpdatePrice), reader.ReadToEnd());
}
}
{
WebRequest request = asyncResult.AsyncState as WebRequest;
WebResponse response = request.EndGetResponse(asyncResult);
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
//this.lbPrice.Text = "价格:" + reader.ReadToEnd();
//在异步更新UI可以这样使用
lbPrice.Dispatcher.BeginInvoke(new UpdatePriceDelegate(UpdatePrice), reader.ReadToEnd());
}
}
直接写lbprice.text等于返回内容,是有错误的。
在多线程异步更新问题上,在winform中可以用Control.Invoke,
而在silverlight当中,DependencyObject 类有一个属性 Dispatcher,可以通过它来更新相关 UI 对象。
代码如下:
代码
void ResponseReady(IAsyncResult asyncResult)
{
WebRequest request = asyncResult.AsyncState as WebRequest;
WebResponse response = request.EndGetResponse(asyncResult);
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
//this.lbPrice.Text = "价格:" + reader.ReadToEnd();
//在异步更新UI可以这样使用
lbPrice.Dispatcher.BeginInvoke(new UpdatePriceDelegate(UpdatePrice), reader.ReadToEnd());
}
}
//委托
private delegate void UpdatePriceDelegate(string price);
private void UpdatePrice(string price)
{
lbPrice.Text = "price:" + price;
}
{
WebRequest request = asyncResult.AsyncState as WebRequest;
WebResponse response = request.EndGetResponse(asyncResult);
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
//this.lbPrice.Text = "价格:" + reader.ReadToEnd();
//在异步更新UI可以这样使用
lbPrice.Dispatcher.BeginInvoke(new UpdatePriceDelegate(UpdatePrice), reader.ReadToEnd());
}
}
//委托
private delegate void UpdatePriceDelegate(string price);
private void UpdatePrice(string price)
{
lbPrice.Text = "price:" + price;
}
2.在设计Grid内容控件的时候,设置长度,高度是不能加单位的,否则会报错,如下图: