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?
@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);
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With