Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF C# - Get inline formated bold Text from TextBlock

I'm adding some TextBlock elements to Border elements in a StackPanel. I'm adding and formating the text of the TextBlock by adding Inlines.

When clicked, I want to get the formated text of the TextBlock.Here is my code.

public void addText()
{
    TextBlock myText = new TextBlock();
    myText.Inlines.Add(new Bold(new Run("Hello ")));
    myText.Inlines.Add("World!");

    Border myBorder = new Border();
    myBorder.Child = myText;
    myBorder.MouseDown += new MouseButtonEventHandler(Border_Clicked);

    myStackPanel.Children.Add(myBorder);
}

private void Border_Clicked(object sender, MouseButtonEventArgs e)
{
    //Border senderBox = (Border)sender;
    //TextBlock senderText = (TextBlock)senderBox.Child;
    //Bold inline = (Bold) senderText.Inlines.ElementAt(0);
    // How to Output "Hello "?
}

Border_Clicked should output "Hello ". As you can see I'm able to get to the bolded Text but how can I ouput it?

like image 431
St. Helen Avatar asked May 09 '16 11:05

St. Helen


2 Answers

@Helen, There is a way to get the Text from the TextPointer using TextRange. Try this code

void myBorder_MouseDown(object sender, MouseButtonEventArgs e)
{
    var senderBox = (Border)sender;
    var senderText = (TextBlock)senderBox.Child;
    var inline = (Bold)senderText.Inlines.ElementAt(0);

    var textRange = new TextRange(inline.ContentStart, inline.ContentEnd);
    Console.WriteLine(textRange.Text);
}
like image 197
Davy Avatar answered Oct 08 '22 09:10

Davy


Is the problem to get text out of Bold element?

private void Border_Clicked(object sender, MouseButtonEventArgs e)
{
    var border = (Border)sender;
    var textBlock = (TextBlock)border.Child;
    var bold = (Bold)textBlock.Inlines.ElementAt(0);

    // How to Output "Hello "?

    // try
    var output = ((Run)bold).Text;
    // or rather (because Bold is a wrapper)
    var output = ((Run)bold.Inlines[0]).Text;
}

If you can add inline like this

myText.Inlines.Add(new Run("Bold text") { FontWeight = FontWeight.Bold });

then it's

var run = (Run)textBlock.Inlines[0];
var output = run.Text;
like image 38
Sinatr Avatar answered Oct 08 '22 08:10

Sinatr