How can I bind a WPF TextBlock to a text file? I want for the TextBlock to display the content of the file.
Asked
Active
Viewed 7,528 times
3 Answers
2
You need to read the file into a string in memory and bind to that string instead.
View model:
class ViewModel
{
public string FileText { get; set; }
public void ReadFile(string path)
{
FileText = File.ReadAllText(path);
}
}
XAML:
<TextBlock Text="{Binding FileText}"/>

Aviad P.
- 32,036
- 14
- 103
- 124
0
This post describes a custom markup extension that, once defined, lets you include the content of a file via XAML:
<Window
x:Class="WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpf="clr-namespace:WPF">
<TextBlock Text="{wpf:Text 'Assets/Data.txt'}" />
</Window>

Community
- 1
- 1

Petter Hesselberg
- 5,062
- 2
- 24
- 42