如何使用外部文本文件填充文本框并在此之后添加单词

时间:2014-05-14 19:29:47

标签: c# visual-studio visual-studio-2012 windows-store-apps

我正在尝试使用外部文本文件中的数据填充visual studio 2012文本框,然后,当您执行该程序时,您应该能够将更改写入此TextBox并将其保存在那里,但我得到了错误,在屏幕截图中说明。而且,我在虚拟机上运行Windows 8!

[screenshot]:http://i.imgur.com/NkZU38C.png“截图

以下是填写文本框的代码:

private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        LoadWords(@"Assets\AdminPageKS1words.txt");

    }

    async private void LoadWords(string filename)
    {
        var wordList = new List<String>();
        // this method reads line separated words from a text file and populates a List object // 
        Windows.Storage.StorageFolder localFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
        // begin the file read operation 
        try
        {
            // open and read in the word list into an object called words 

            StorageFile sampleFile = await localFolder.GetFileAsync(filename);
            var words = await FileIO.ReadLinesAsync(sampleFile);
            // add each word returned to a list of words declared 
            // globally as List wordList = new List();
            foreach (var word in words) 
            { 
                wordList.Add(word); 
            }
            List1.ItemsSource = wordList;
        }
        catch (Exception)
        {
            // handle any errors with reading the file
        } 

以下是SAVE按钮的代码:

async private void SaveButton_Click(object sender, RoutedEventArgs e)
    {

 // locate the local storage folder on the device
  Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

// create a new text file in the local folder called “File.txt”
StorageFile sampleFile = await localFolder.CreateFileAsync("File.txt",CreationCollisionOption.ReplaceExisting);

// write text to the file just created – text comes from a textblock called wordlistBox
await FileIO.WriteTextAsync(sampleFile, List1.Text); 

 // display a message saying that file is saved.
messageLabel.Text = keystage + "File saved";

    }

    public string keystage { get; set; }

2 个答案:

答案 0 :(得分:1)

正如错误消息所示,List1(a TextBox)没有ItemsSource属性。它有Text属性。

但这不是唯一的问题。因为您的wordList对象是IList。所以你需要把它变成一个普通的字符串。

一种解决方案是:

List1.Text = string.Join(Environment.NewLine, wordlist);

将连接所有行以及其间的换行符。

还要确保在AcceptsReturn设置为true的情况下正确配置TextBox,以便显示换行符。

答案 1 :(得分:0)

我看到List1是TextBox,而不是ListBox,请尝试:

.......
string text="";
foreach (var word in words) 
            { 
                text+=word+" "; 
            }
      List1.Text=text;

或者,您可以定义ListBox listbox1:

 foreach (var word in words) 
            { 
                wordList.Add(word); 
            }
            listbox1.ItemsSource = wordList;