如何在列表中显示字符串到textblock?

时间:2015-07-17 08:37:25

标签: c# xaml

我想显示文本文件中的文本,我已将其拆分为列表到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>

1 个答案:

答案 0 :(得分:1)

您的ItemsControl需要包含文本块的ItemTemplate

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

或者,如果您只想显示字符串DisplayMemberPath,则可以使用start

  <ItemsControl ItemsSource="{Binding Data}" DisplayMemberPath="start" />