读取给定文件 Windows Phone 8.1

Read given file Windows Phone 8.1

我尝试根据用户文本框输入读取某个文件

案例: 有 2 个文件:AB。用户在 "A" 中键入 TextBox.Text 属性 并单击按钮从文件加载数据。

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

问题: 当 fileName 被硬编码到函数中时,这工作正常。 如何让它读取 SearchBox.Text 属性 来查找想要的文件?如果我使用 string name = SearchBox.Textstring fileName = name + ".json" 它 returns 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();          
        }

旁注:这将是一个为其中一个游戏显示 "hero information" 的应用程序,因此对象命名。

您不能从后台线程访问 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)