【问题标题】:Bind to resource text file绑定到资源文本文件
【发布时间】:2016-12-09 14:40:32
【问题描述】:

我想将一个文本块绑定到一个作为资源编译的文本文件。有没有办法将它像图像一样与源属性和包 uri 绑定?

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

【问题讨论】:

    标签: wpf xaml data-binding text-files


    【解决方案1】:

    嗯,你当然不能以完全相同的方式做到这一点。如果你试试这个:

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

    ...它只是将 pack uri 显示为文本——不是你想要的。

    一种可能的解决方案是创建自己的MarkupExtension。例如:

    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();
                }
            }
        }
    }
    

    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>
    

    当然,假设命名的文本文件是一个资源:

    进一步阅读:

    【讨论】:

    • 我应该在那里处理 IO/异常并忽略所有异常吗?
    • 我想是的,是的。我没有看到其他任何地方你可能有机会这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    相关资源
    最近更新 更多