2012-07-20 113 views
0

我在Windows Phone 7中有一個列表框,我想在列表框中顯示孤立存儲文件的列表,當我從列表框中選擇文件時,我應該能夠從文件。Windows Phone 7列表框

這裏是我的代碼:

ListBoxItem lbi = (ListBoxItem)listBox1.SelectedItem; 
string t = (string)lbi.Content; 

using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) 
using (var sr = new StreamReader(store.OpenFile(t, FileMode.Open, FileAccess.Read))) 
{ 
    textBlock2.Text = sr.ReadToEnd(); 
} 

和對文件綁定到列表:

var appstorage = IsolatedStorageFile.GetUserStoreForApplication(); 
string[] filename = appstorage.GetFileNames(); 
listBox1.ItemsSource = filename; 

但是當我嘗試了申請,根據SelectionChanged事件中,我得到一個錯誤:

Invalid cast exception on ListBoxItem lbi = (ListBoxItem)listBox1.SelectedItem;

現在最終的問題是,我該如何在l中檢索確切的文件名ist box當SelectionChanged事件被觸發時,這樣文件名可以被流讀取器使用?

回答

0

您對IEnumerable<string>string[])有約束力,列表框不會將這些項目轉換爲ListBoxItem's它們只是工廠字符串的常規舊運行。

所以,你應該做的:

string t = (string)listBox1.SelectedItem; 

using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) 
using (var sr = new StreamReader(store.OpenFile(t, FileMode.Open, FileAccess.Read))) 
{ 
    textBlock2.Text = sr.ReadToEnd(); 
} 
+0

這解決我的問題,戴的帽子。 謝謝! – user1512186 2012-07-20 16:05:01