簡體   English   中英

在WP8上以設計模式從MVVM Light ViewModel訪問Web

[英]Accessing the web from a MVVM Light ViewModel in design mode on WP8

我正在將MVVM Light框架與MVVM ViewModelLocator一起使用,並且具有如下方法:

protected override System.Threading.Tasks.Task<string> GetFromUri(string uriString)
{
    string outString;

    TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(uriString, UriKind.RelativeOrAbsolute));
    request.Method = "GET";
    request.BeginGetResponse((result) =>
    {
        WebResponse response = request.EndGetResponse(result);
        using (var inStream = response.GetResponseStream())
        {
            long length = inStream.Length;
            byte[] inBytes = new byte[length];
            inStream.Read(inBytes, 0, (int)length);
            outString = Encoding.UTF8.GetString(inBytes, 0, (int)length);
            tcs.TrySetResult(outString);
        }
    }
    , null);

    return tcs.Task;
}

...我正嘗試在“設計模式”下​​使用。 似乎最好的稱呼是在

if (IsInDesignModeStatic)
{
    //....
}

在ViewModel的構造函數中。 但是,它失敗並顯示“跨線程”異常。 將調用包裝在Application.Current.RootVisual的Dispatcher.Invoke中,使我們通過“跨線程”異常,但結果是“無法訪問已處置的對象”(引用調度程序對象)。

使用Windows Phone 8上的MVVM Light框架,您可以在設計模式下執行Web請求嗎(為什么看不到任何技術原因)? 如果ViewModel構造函數是執行此操作的錯誤位置,那么正確的位置是什么?

該問題源自使用HttpWebRequest。 重寫以使用HttpClient(NuGet上可用的System.Net.Http庫)解決了此問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM