我正在向TextBlock
中的Border
元素添加一些StackPanel
个元素。
我正在通过添加TextBlock
添加并格式化Inlines
的文字。
点击后,我想获取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”。正如你所看到的,我能够得到粗体文本,但我怎么能输出呢?
答案 0 :(得分:2)
@Helen,有一种方法可以使用TextRange从TextPointer获取Text。试试这段代码
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);
}
答案 1 :(得分:1)
问题是从Bold
元素中获取文本吗?
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;
}
如果您可以像这样添加内联
myText.Inlines.Add(new Run("Bold text") { FontWeight = FontWeight.Bold });
然后是
var run = (Run)textBlock.Inlines[0];
var output = run.Text;
答案 2 :(得分:0)
无法在MessageBox中控制字体特征。我认为你应该考虑创建一个"自定义MessageBox"。像这样:
<Window x:Class="WpfApplication1.CustomMessageBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
SizeToContent="WidthAndHeight" MaxWidth="400">
<Grid x:Name="GridContent" Margin="10">
</Grid>
</Window>
所以在它的构造函数中你可以发送你的Bold:
private Bold _text;
public CustomMessageBox(Bold formattedText)
{
_text = formattedText;
GridContent.Child = _text;
}
使用:
private void Border_Clicked(object sender, MouseButtonEventArgs e)
{
Border senderBox = (Border)sender;
TextBlock senderText = (TextBlock)senderBox.Child;
Bold inline = (Bold) senderText.Inlines.ElementAt(0);
var customMsgBox = new CustomMessageBox(inline);
customMsgBox.ShowModal();
}
现在,如果您不确定它将永远是一个Bold对象,我建议您将格式化的文本保存为XML并在之后加载。看看这个:showing formatted text