c# - WPF C# - 从 TextBlock 获取内联格式的粗体文本

标签 c# wpf visual-studio textblock

我正在向 StackPanel 中的 Border 元素添加一些 TextBlock 元素。 我通过添加 Inlines 添加并格式化 TextBlock 的文本。

单击时,我想获取 TextBlock 的格式化文本。这是我的代码。

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 应该输出“Hello”。如您所见,我可以访问粗体文本,但如何输出它?

最佳答案

@Helen,有一种方法可以使用 TextRange 从 TextPointer 获取文本。试试这段代码

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);
}

关于c# - WPF C# - 从 TextBlock 获取内联格式的粗体文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37114131/

相关文章:

c# - 参数化返回类型是否需要泛型方法签名?

sql-server - 执行 SSIS 包给出 System.IO.IOException

asp.net - visual studio 没有 asp.net 的可能性

c# 无法播放wav文件

c# - 无法将方法组 'Read' 转换为非委托(delegate)类型 'bool'

c# - 应用程序在运行异步任务时挂起

c# - 两个角度的弧度差?

c# - 绑定(bind) - 回调被调用两次

c# - 自定义面板内的项目未正确排列

c - 来自平面汇编器的 Visual Studio LNK1107 : invalid or corrupt file - . obj (COFF)