且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将文本文件绑定到XAML ListBox控件

更新时间:2022-02-25 17:46:48

经过无数小时的阅读文档,搜索和提出问题之后;我设法自己解决了这个问题.

After what seemed to be endless hours of reading through documentation, searching, and asking questions; I managed to figure this out for myself.

以下是在我遇到的情况下可以正常使用的代码:

Below is the code that works just as I need it to in my situation:

XAML:

<ListBox Name="NotesList">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Filename}" />
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>

隐藏代码:

    public class NoteView
    {
        public string Filename { get; set; }
        public string Contents { get; set; }
    }

    /// <summary>
    /// Invoked when this page is about to be displayed in a Frame.
    /// </summary>
    /// <param name="e">Event data that describes how this page was reached.  The Parameter
    /// property is typically used to configure the page.</param>
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        var noteList = new ObservableCollection<NoteView>();

        for (int i = 0; i < 10; i++)
        {
            noteList.Add(new NoteView { Filename = "Sample note " + i });
        }

        NotesList.ItemsSource = noteList;
    }