在主页上将文件内容显示为标题,而不是文件名

本文关键字:标题 文件名 显示 主页 文件 | 更新日期: 2023-09-27 18:01:58

我想创建一个应用程序,你有一个显示所有笔记的主页面,你可以创建一个新的笔记或从列表中选择一个笔记。

现在,它显示所有的文件名,如Sample1.txt, Sample2.txt。

我希望它像这样显示:


这是一个很棒的应用。

提醒我买牛奶

不像这样:


Sample1.txt

Sample2.txt

Sample3.txt

Sample4.txt

下面是显示列表的代码:
    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
    { 
        using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication()) 
        { 
            this.NotesListBox.ItemsSource = store.GetFileNames(); 
        } 
    } 

这里是主xaml

的绑定
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <ListBox x:Name="NotesListBox" SelectionChanged="Notes_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <TextBlock Text="{Binding}" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>

我想知道这个…谢谢!

在主页上将文件内容显示为标题,而不是文件名

一种非常快速而又非常肮脏的解决方案是替换

this.NotesListBox.ItemsSource = store.GetFileNames(); 

var filesNames = store.GetFileNames();
var titles = new List<string>();
foreach (var fileName in fileNames)
{
    using (var sr = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, isf)))
    {
        titles.Add(sr.ReadLine());
    }
}
this.NotesListBox.ItemsSource = titles;

这样你的列表框将列出所有文件的第一行。

然而,这个解决方案的问题是,您在文件中的列表框中的项之间有一个链接。一个更好的解决方案是为你的笔记引入一个模型,例如:

public class Note
{
    public string Title { get; set; }
    public string Content { get; set; }
    public string FileName { get; set; }
}

你可以使用这个模型来加载所有的笔记,并把它放在列表框中,像这样:

// put this in your view class
private List<Note> _notes;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
{ 
    _notes = new List<Note>();
    var filesNames = store.GetFileNames();
    foreach (var fileName in fileNames)
    {
        using (var sr = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, isf)))
        {
            var note = new Note();
            note.FileName = fileName;
            note.Title = sr.ReadLine();
            note.Body = sr.ReadToEnd();
            _notes.Add(note);
        }
    }
    this.NotesListBox.ItemsSource = _notes;
} 
在你的xaml中,你需要替换
<TextBox Text="{Binding}"/>

<TextBox Text="{Binding Title}"/>

在您的SelectionChanged处理程序中,您现在可以像这样引用注释:

private void Notes_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    foreach (Note note in e.AddedItems)
    {
        MessageBox.Show(note.Body);
    }
}

一个更好的解决方案是使用mvvm。但现在看来,这可能太过分了。

祝你好运!