Bind WPF TextBlock to text file

白昼怎懂夜的黑 提交于 2019-12-31 04:10:19

问题


How can I bind a WPF TextBlock to a text file? I want for the TextBlock to display the content of the file.


回答1:


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}"/>



回答2:


If you want the text to be formatted my inline markup you could look at the sub-class of TextBlock I made here. There is a convertor between a String of xaml markup and an InlineCollection(actually a generic list of Inlines) too.




回答3:


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>


来源:https://stackoverflow.com/questions/1995325/bind-wpf-textblock-to-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!