Reputation:
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/..."/>
Upvotes: 1
Views: 1119
Reputation: 5498
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:
Upvotes: 1