Bind to resource text file

自作多情 提交于 2019-12-11 06:25:47

问题


I want to bind to a text block to a text file which is compiled as a resource. Is there a way to bind it like a image with the source property and a pack uri?

<Image Source="pack://application:,,,/Properties/..."/>

回答1:


Well, you certainly can't do it exactly the same way. If you try this:

<TextBox Text="pack://application:,,,/Properties/..."/>

...it just displays the pack uri as text -- not what you want.

One possible solution is to create your own MarkupExtension. For example:

public class TextExtension : MarkupExtension
{
    private readonly string fileName;

    public TextExtension(string fileName)
    {
        this.fileName = fileName;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        // Error handling omitted
        var uri = new Uri("pack://application:,,,/" + fileName);
        using (var stream = Application.GetResourceStream(uri).Stream)
        {
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
    }
}

Usage from 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>

Assuming, of course, that the named text file is a resource:

Further reading:

  • Markup Extensions for XAML Overview
  • MarkupExtension Class


来源:https://stackoverflow.com/questions/41062844/bind-to-resource-text-file

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