绑定到资源文本文件 [英] Bind to resource text file

查看:184
本文介绍了绑定到资源文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


解决方案

嗯,你当然无法做到这一点同样的方式。如果您尝试这样做:

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

...它只显示包uri作为文本 - 不是你想要的。 >

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

  public class TextExtension:MarkupExtension 
{
private readonly string fileName;

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

公共覆盖对象ProvideValue(IServiceProvider serviceProvider)
{
//错误处理省略
var uri = new Uri(pack://应用程序:,,, /+ fileName);
使用(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>

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





进一步阅读:




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

解决方案

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:

这篇关于绑定到资源文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆