0

I am trying to open an xaml-file (FlowDocument) in a WPF RichTextBox when the program starts by putting code in MainWindow(). I have tried several examples from the web, for example this one and several similiar ones, but the program does not even open. When I have put the exe-file and the xaml-file in a folder and click on the exe-file nothing happens. Here is all code in the cs-file:

using System.IO;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            FileStream fs = new FileStream("test.xaml", FileMode.Open, FileAccess.Read);
            FlowDocument content = XamlReader.Load(fs) as FlowDocument;
            richTextBox1.Document = content;
        }
    }
}

And all code in the xaml-file:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <RichTextBox Name="richTextBox1" Width="300" Height="300" />
    </Grid>
</Window>

Content of 'test.xaml' (in the same folder as the program):

<FlowDocument>
  <Paragraph>I am an XAML-dokument.</Paragraph>
</FlowDocument>

What code will open an xaml-file in a WPF RichTextBox and interpret the FlowDocument markup when the program starts?

6
  • 2
    do some rudimentary try catch block .... I bet that xaml's file lack of namespace so it cannot be loaded Commented Oct 15 at 7:47
  • 2
    Or just get the exception when you run the application in debugger. It should be <FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"><Paragraph>I am an XAML-dokument.</Paragraph></FlowDocument> Commented Oct 15 at 8:54
  • 1
    Also make sure to close the file after reading: using (var fs = File.OpenRead("test.xaml")) { richTextBox1.Document = XamlReader.Load(fs) as FlowDocument; } Commented Oct 15 at 8:56
  • 1
    Adding a namespace solved the problem. Thanks! Commented Oct 15 at 10:06
  • 2
    Ah, here's a legit duplicate: FlowDocument sourced from external resource, specifically this answer by Louis Somers details the required namespace xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> Commented Oct 17 at 18:08

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.