Search code examples
wpfbuttonflowdocumentword-wrapwrappanel

WPF: How to embed button inside text flow (wrap text around button)?


I'd like an advice to the following problem: I want to embed a Button into a text flow, but when I embed a Button and Label (or TextBlock) into the WrapPanel, I get the first figure:

alt text http://sklad.tomaskafka.com/files/wpf-wrappanel-problem.png

I think that one of solutions could be FlowDocument, but I feel that this is far too heavy for a control simple like this (which could be used in several hundred instances). Do you have some other ideas about how to implement this? Thank you!

EDIT: One solution could be the following (I didn't know it was possible to put more stuff into TextBlock), but I would lose the ability to bind (which I need):

<TextBlock TextWrapping="Wrap">
    <Span>
        <Button x:Name="MyButton" Command="{Binding Path=MyCommand}" Content="+" />
        <Run x:Name="MyLabel" Text="{Binding Path=Subject}" />
        <!--
        Problem: binding makes following error:
        A 'Binding' cannot be set on the 'Text' property of type 'Run'. 
        A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
        -->
    </Span>
</TextBlock>

Solution

  • I found that implementing BindableRun correctly is pretty tricky - and almost all other available implementations will cause an exception from wpf layouting engine when the bound content changes from null to something non-null - see this problem, keyword "Collection was modified; enumeration operation may not execute."

    Corrrect implementation from Microsoft is here - it shows how tricky this really is.