UWP: How to bind a Textblock to a .txt file?

Viewed 97

The file "sample.txt" is in the Assets folder, and contains a single line with the text "hello, world". I would like to bind its content to a Textblock control.

2 Answers

Set the Text property of the TextBlock to the contents of the file:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();

        this.Loaded += async (s, e) =>
        {
            const string Filename = @"Assets\sample.txt";
            var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            var file = await folder.GetFileAsync(Filename);
            textBlock1.Text = await File.ReadAllTextAsync(file.Path);
        };
    }
}

Extract the text from the file using File.ReadAllText and assign it to a property on a class that implements INotifyPropertyChanged. Bind this property to the TextBlock.Text property.

Your view model:

public class MainPageViewModel : INotifyPropertyChanged
{
    private string text;

    public event PropertyChangedEventHandler PropertyChanged;

    public string Text
    {
        get => this.text;
        set
        {
            this.text = value;
            this.OnPropertyChanged(nameof(this.Text))
        }
    }

    protected void OnPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

Your view:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        
        this.Loaded += async (s, e) =>
        {
            var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            var file = await folder.GetFileAsync(@"Assets\sample.txt");

            this.DataContext = new MainPageViewModel
            {
                Text = await File.ReadAllTextAsync(file.Path),
            };
        };
    }
}

Within your MainPage XAML:

<TextBlock Text="{x:Bind Text}"

To detect changes in the txt-file, use FileSystemWatcher.

Related