【问题标题】:Read given file Windows Phone 8.1读取给定文件 Windows Phone 8.1
【发布时间】:2015-05-11 12:39:36
【问题描述】:

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

案例: 有 2 个文件:AB。用户在TextBox.Text 属性中输入“A”,然后单击按钮从文件加载数据。

文件由 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();          
        }

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多