HOW-TO: Creating a simple UserControl for displaying a FlowDocument

Hello. This is my first post about WPF.

This how-to will show you how to create a UserControl in which you can show a FlowDocument by passing a string containing the FlowDocument. It also allows Data Binding.

Lets start.

1. Create a UserControl called FlowDocumentViewer in Expression Blend (you can also do this in Visual Studio if you want) and add a FlowDocumentScrollViewer to LayoutRoot. Name it flowDocument (you can name it like you want, but I will be using this name in this guide). Your structure should be as follows:

Structure

2. Now, open the project in Visual Studio and add the following code to your FlowDocumentViewer.xaml.cs:

        public static readonly DependencyProperty ContentFlowDocumentStringProperty = DependencyProperty.Register(
            "ContentFlowDocumentString",
            typeof(string),
            typeof(FlowDocumentViewer),
            new FrameworkPropertyMetadata(null,
                FrameworkPropertyMetadataOptions.AffectsRender,
                new PropertyChangedCallback(DescriptionFlowDocumentUI.OnContentChanged)
            )
        );

        private static void OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            FlowDocumentViewer control = (FlowDocumentViewer)d;
            control.flowDocument.Document =
                (System.Windows.Documents.FlowDocument)System.Windows.Markup.XamlReader.Load(
                    new MemoryStream(System.Text.UTF8Encoding.Default.GetBytes((string)e.NewValue))
                );
        }

        public string ContentFlowDocumentString
        {
            get { return (string)GetValue(ContentFlowDocumentStringProperty); }
            set { SetValue(ContentFlowDocumentStringProperty, value); }
        }

Lets see what this code does.

a) We added a DependencyProperty called ContentFlowDocumentStringProperty to our class. This DependencyProperty “points” at ContentFlowDocumentString property, as well as it tells, that this property of type string and we registered a callback function (OnContentChanged), which will be triggered when ContentFlowDocumentString is changed. Note that FrameworkPropertyMetadataOptions.AffectsRender piece of code. This tells WPF, that when this property is changed it affects the UI looks, so that WPF knows he has to render something.

b) The OnContentChanged function is called whenever our DependencyProperty is changed. Here we do the actual work of changing the FlowDocument in our control. We get the instance as an argument (DependencyObject d, which we cast to FlowDocumentViewer explicilty) and we create a new FlowDocument from the newly assigned string ((string)e.newValue).

c) Finally we added the actual property – ContentFlowDocumentString. See those GetValue and SetValue? Don’t be surprized, it is how DependencyProperties work. You don’t have a special (private) field in your class for them. WPF does all the work for you.

Well, that is pretty much it.

The usage is simple:

FlowDocumentViewer fdv = new FlowDocumentViewer();
fdv.ContentFlowDocumentString = stringContainingFlowDocumentXAML;

Or if you want to use data binding, it is absolutely similar to casual binding in WPF:

Binding b = new Binding();
b.Source = myBindingSource;
b.Path = new PropertyPath("PathToProperty");
FlowDocumentViewer fdv = new FlowDocumentViewer();
fdv.SetBinding(FlowDocumentViewer.ContentFlowDocumentStringProperty, b);

If you have questions / remarks / etc. feel free to post them. I will try to answer.

18 Responses to HOW-TO: Creating a simple UserControl for displaying a FlowDocument

  1. OUNI Mehdi says:

    Hello.
    I read
    I have a problem about the display of two usercontrol in one window or page.
    So I have two usercontrol and each of them contain differents data (property).
    I like when I click in the data on the primary usercontrol, the secondary display informations about the selected data.
    If you have an example who help me or indication please can you make to me.
    Thanks

  2. What?.. Didn’t understand what you are trying to say… I can’t even understand how is it connected to this post?..

  3. Thank you for sharing your thoughts. I truly appreciate your efforts and I am waiting for your next write
    ups thanks once again.

  4. If some one needs expert view on the topic of blogging then i suggest
    him/her to pay a quick visit this web site, Keep up the fastidious
    job.

  5. Attractive section of content. I just stumbled upon your weblog and in accession capital to assert that I acquire
    actually enjoyed account your blog posts. Any way I’ll be subscribing to your augment and even I achievement you access consistently fast.

  6. I don’t know whether it’s just me or if perhaps everyone else experiencing
    issues with your blog. It appears as though some
    of the written text on your posts are running off the screen.
    Can somebody else please comment and let me know if this is happening to them too?
    This may be a issue with my internet browser because I’ve had this happen before. Thank you

  7. Your aspects of start collections, active disposition of figures, territorial
    gain and many others refer to the position advantages throughout chess.
    Through now, the game is afflicted, since they
    are shedding his or her target, and also usually can be taking tilt, that make the sacrificing period very much
    trickier in order to crack.

  8. winoptions says:

    In regard to winoptions, a similar is true, other than the market doesn’t have to go greatly with either route to find out some sort of profit – just one tick in either case can earn you a specified sum of money. As you can see, this is similar to exactly how some other expense cars for instance shares and commodities are bought and sold, yet with no all the potential as well as unstable damage connected with these kinds of investments. Likewise, in case a great trader ordered any fit solution, a great expense the place that the speculator considers your winoptions may truly slide within worth, in case it lets you do, your trader can be once more “in the money” due to the fact, bidirectionally, the option performed as the investor expected. Up until ’08, there seemed to be little by
    means of established enforceable laws.

  9. go back says:

    While different programs may well seek to seriously people along with
    large affiliate marketor payouts as well as reduced limits,
    merely go back provides the choice to honestly profit from go back.
    That is an issue that several go back professionals ignore
    to consider after they get into nighttime
    deals. Seasoned traders, together with backdrop go back shares, selection expertise,
    or maybe get dealt foreign exchange in the past will relish this unique
    go back platform due to the versatility as well as steadiness.

  10. onbling says:

    Instead of acquiring to travel to some sort of city where by wagering is usually authorized, or even likely
    to a great Indian native gambling establishment,
    on the convenience of your property, it is possible to log in the gambling house you need to in order to engage in.
    Maths can be a subject most ended up pushed to adopt in institution, a thing many people genuinely would
    not including.

  11. Zoomtrader says:

    When the current market won’t proceed on your path, you can drop 90% or maybe more of one’s
    original expenditure. Just like shares as well as provides, alternatives are generally
    thought to be a new safety measures and so are consequently a joining long term
    contract relating to the a couple of get-togethers. A new call alternative is usually an alternative you spend your hard earned dollars with since
    you assume that the marketplace will probably climb.

  12. Distinctive by classic options, these kind of have got distinct charges, levels of danger, affiliate marketer payouts,
    and also an purchase practice and also liquidity construction.
    The features involving dealing binary Options
    is actually you are sure that how much a person have make or perhaps drop.
    Your volatility with the industry isn’t going to make it 100% expected; binary Options is a powerful along with innovative new way for people to business in addition to make money using the actual convenience of the own households.

  13. Usually I wouldn’t read write-up on blogs and forums, even so desire to express that this particular write-up pretty urged everyone to perform consequently! The crafting flavor continues to be surprised us. Thank you so much, great publish.

  14. Entertainment, meals, and also relaxation along with
    fun. The 1st individual for you to indicate down all there
    difficulties, may be the champion of the activity.

  15. You’ll see a huge selection of signup bonuses that you can get including first-time sign-up bonuses, match up bonus deals, simply no downpayment advantage offers, along with special offers simply inclined to those that tend to be regular in addition to dedicated people. Really many mobile devices injury digital camera slot machines (especially just before GSM insurance policy coverage, while NMT had been any superhit), but My partner and i haven’t much noticed almost any stories connected with players to be able to gain a advantage the actual aladdins Gold casino using this
    strategy in addition to distance themself your money.

  16. With bad credit bad credit consolidation loanss. On the brighter side, bad credit pending
    you need to go to the dealer without being in the dark.

    If you are unemployed or do not want to deal with buy-here, pay-here
    car lots. I want to refinance your car.

  17. Buy one for your neighbour and race them along the path or use Big Trak to send messages to
    your wife in the other room. The only safe
    way to avoid this result is to have the ILIT apply for and own
    the policy from the outset (even if done with the insured.
    The characters in SOCOM 4 are a diverse bunch, including a woman.

  18. fixed rate loans

    HOW-TO: Creating a simple UserControl for displaying a FlowDocument | Jefim Borissov

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: