【发布时间】:2016-12-09 14:40:32
【问题描述】:
我想将一个文本块绑定到一个作为资源编译的文本文件。有没有办法将它像图像一样与源属性和包 uri 绑定?
<Image Source="pack://application:,,,/Properties/..."/>
【问题讨论】:
标签: wpf xaml data-binding text-files
我想将一个文本块绑定到一个作为资源编译的文本文件。有没有办法将它像图像一样与源属性和包 uri 绑定?
<Image Source="pack://application:,,,/Properties/..."/>
【问题讨论】:
标签: wpf xaml data-binding text-files
嗯,你当然不能以完全相同的方式做到这一点。如果你试试这个:
<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>
当然,假设命名的文本文件是一个资源:
进一步阅读:
【讨论】: