我试图用外部文本文件中的数据填充visual studio 2012文本框,在此之后,当您执行程序时,您应该能够编写对该文本框的更改并将其保存在那里,但我得到错误,在屏幕截图中说明。而且,我是在虚拟机上运行Windows 8的!
[截图]:https://i.stack.imgur.com/zFSi4.png "截图
下面是填充文本框的代码:
private void Page_Loaded(object sender, RoutedEventArgs e)
{
LoadWords(@"AssetsAdminPageKS1words.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; }
如错误信息所示,List1
(a TextBox
)没有ItemsSource
属性。它有Text
的性质。
但这不是唯一的问题。因为你的wordList
对象是一个列表。所以你需要把它转换成一个普通的字符串。
List1.Text = string.Join(Environment.NewLine, wordlist);
,它将所有行连接在一起,中间有换行符。
还要确保您的TextBox配置正确,AcceptsReturn
设置为true,以便它将显示换行
我看到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;