阅读给定文件Windows Phone 8.1

时间:2015-05-11 12:39:37

标签: c# windows-phone-8 windows-phone-8.1

我尝试根据用户TextBox输入

读取某个文件

案例: 共有2个文件:AB。用户类型" A"进入TextBox.Text属性并单击按钮以从文件加载数据。

文件由JSONConverter处理,然后显示在UI中。

问题: 当fileName被硬编码到函数中时,这可以正常工作。 如何让它读取SearchBox.Text属性以查找所需文件?如果我使用string name = SearchBox.Textstring fileName = name + ".json"它会返回The application called an interface that was marshalled for a different thread. - 可能是因为我尝试从UI中读取为后续执行的UI线程保留的内容? (我是新的,我尽可能地了解错误)。

 public async void DownloadDataAsync() 
        {
         // string fileName = SearchBox.Text; This doesn't work - it doesn't give compliation errors, 
            string fileName = "A.json"; // If this is set "hardcoded" the program executes correctly.
            StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\HerodataJSON\" + fileName);
            string fileContent;
            using (StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync()))
            fileContent = await sRead.ReadToEndAsync();              

            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {                    
                Herodata hero = JsonConvert.DeserializeObject<Herodata>(fileContent);
                HeroName.Text = hero.Heroname;
                CounteredByList.Text = String.Join("\r\n", hero.Counteredby);
                CountersList.Text = String.Join("\r\n", hero.Counters);
                HeroPortrait.Source = new BitmapImage(new Uri(hero.IMGurl));
            });
        }

        private void BtnDownloadData_Click(object sender, RoutedEventArgs e)
        {            
            Task t = new Task(DownloadDataAsync);
            t.Start();          
        }

旁注:这将是一个显示&#34;英雄信息的应用程序&#34;其中一个游戏,因此对象命名。

1 个答案:

答案 0 :(得分:2)

您无法从后台线程访问UI元素。一个快速解决方法是事先读取值,然后将其传递给您的方法:

private void BtnDownloadData_Click(object sender, RoutedEventArgs e)
{            
    var fileName = SearchBox.Text;
    Task t = new Task(() => DownloadDataAsync(fileName));
    t.Start();          
}

将其他方法的签名更改为:

public async void DownloadDataAsync(string fileName)