[WPF] Button following text in a TextBlock

Nick Luo 21 Reputation points
2021-09-14T08:27:52.763+00:00

I have a TextBlock which contains a button, and I expect that the button will follow the content text of TextBlock.
(The button should be attached to the end of the text of TextBlock.)

My working demo code:
131867-microsoftteams-image-1.png

Where "gdRoot" is an arbitrary Grid in XAML.
This code works fine until I change the content of the TextBlock.
Once I change the text of TextBlock, the button disappears.
In real case, the content of TextBlock is bound to a resource, which will change according to the language user selects.
And after "property change" event is triggered, or the text is re-assigned, the button disappears.
As I know, the button is added to the TextBlock's "Inlines" property, and the InlineCollection is intact after "property change" event.

Does anyone know how to avoid button from disappearing?

Thanks in advance.

Developer technologies | Windows Presentation Foundation
0 comments No comments
{count} votes

Answer accepted by question author
  1. Castorix31 91,496 Reputation points
    2021-09-14T09:23:51.787+00:00

    You could do something like :

    TextBlock tb = new TextBlock();
    Run run1 = new Run("Text before the button... ");
    Button btn = new Button();
    btn.Content = "Button";
    
    tb.Inlines.Add(run1);
    tb.Inlines.Add(btn);
    
    gdRoot.Children.Add(tb);
    run1.Text = "New text";
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.