将 WPF TextBlock 绑定到文本文件

发布于 2024-08-16 15:15:12 字数 55 浏览 5 评论 0原文

如何将 WPF TextBlock 绑定到文本文件?我想让 TextBlock 显示文件的内容。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

红玫瑰 2024-08-23 15:15:12

您需要将文件读入内存中的字符串并绑定到该字符串。

查看模型:

class ViewModel
{
    public string FileText { get; set; }
    public void ReadFile(string path)
    {
        FileText = File.ReadAllText(path);
    }
}

XAML:

<TextBlock Text="{Binding FileText}"/>

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}"/>
晨光如昨 2024-08-23 15:15:12

如果您希望将文本格式化为内联标记,您可以查看我制作的 TextBlock 子类 此处。 xaml 标记字符串和 InlineCollection(实际上是 Inlines 的通用列表)之间也有一个转换器。

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.

一城柳絮吹成雪 2024-08-23 15:15:12

这篇文章描述了一个自定义标记扩展,定义后,您可以通过 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>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文