如何在列表中显示字符串到文本块

本文关键字:字符串 文本 显示 列表 | 更新日期: 2023-09-27 18:03:15

我想在Ui(xaml)中显示我已经拆分到列表的文本文件中的文本。我使用数据绑定,但它总是错误的,文本不出现,所以你有任何方法来指导我吗?谢谢,我在通用应用程序

private async void button_click(object sender, RoutedEventArgs e)
{
    string content = "00:00:00;00:00:10;hello'r'n00:00:10;00:00:20;hi";
    string filename = "test.txt";
    // saves the string 'content' to a file 'filename' in the app's local storage folder
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(content.ToCharArray());
    // create a file with the given filename in the local folder; replace any existing file with the same name
    StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    // write the char array created from the content string into the file
    using (var stream = await file.OpenStreamForWriteAsync())
    {
        stream.Write(fileBytes, 0, fileBytes.Length);
    }
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    Stream streams = await local.OpenStreamForReadAsync(filename);
    string text = "";
    List<string> textread = new List<string>();
    using (StreamReader reader = new StreamReader(streams))
    {
        while (text != null)
        {
            text = reader.ReadLine();
            if (text != null)
                textread.Add(text);
        }
    }
    foreach (string stringoutput in textread)
    {
        string[] words = stringoutput.Split(';');
        datas.Add(new Datum { start = words[0], end = words[1], comment = words[2] });
    }
    foreach (Datum temp in datas)
    {
        string a = temp.start;
        string b = temp.end;
        string c = temp.comment;
    }
}
public class Datum
{
    public Datum Data;
    public string start { get; set; }
    public string end { get; set; }
    public string comment { get; set; }
}
public class ViewModel
{
    public ViewModel()
    {
        // data
        var _Data = Enumerable.Range(1, 20)
            .Select(x => x => (string)(x + 'a'));       
        Data = new ObservableCollection<Datum>(_Data);
    }
    public ObservableCollection<Datum> Data { get; private set; }
}

这是XAML的一部分:

        <ItemsControl ItemsSource="{Binding Data}">
                        <TextBlock Text="{Binding start}" />
        </ItemControl>

如何在列表中显示字符串到文本块

您的ItemsControl需要一个包含textblock的ItemTemplate:

<ItemsControl ItemsSource="{Binding Data}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>            
              <TextBlock Text="{Binding start}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

或者,如果您只想显示字符串start:

,您可以使用DisplayMemberPath
  <ItemsControl ItemsSource="{Binding Data}" DisplayMemberPath="start" />