如何解决将特定的Run添加到Windows.UI.Xaml.Controls.TextBlock后,如何以编程方式访问它?
在将特定运行添加到Windows.UI.Xaml.Controls.TextBlock后,我希望能够以编程方式访问特定运行,但由于Name属性是只读的,所以我无法设置运行的名称(允许获取但未设置)。
每次运行都会通过一个循环动态创建(而不是在设计时(xaml)),而且我也不知道索引(i-th),因为它们可以以任何顺序创建。我会知道某个跑步中会出现的单词或关键字,但是除此之外,我别无选择,无法从另一个跑步中识别出一个跑步。
当我单击按钮时,如何以编程方式查找和访问添加到TextBlock的特定运行?
using Windows.UI.Xaml.Controls;
var myTextBlock = new TextBlock();
var someRun = new Run
{
Text = "Some run to start"
};
myTextBlock.Inlines.Add(someRun)
var arandomrun = new Run
{
Text = "A random run with some words"
};
myTextBlock.Inlines.Add(arandomrun)
var anotherRun = new Run
{
Text = "Another run,Could be anything"
};
myTextBlock.Inlines.Add(anotherRun)
private void GetTextButton_Click(object sender,RoutedEventArgs e)
{
// Get the text of any of these above runs in myTextBlock
// I tried "FindName" but since I cannot set the the name of the Run,I cannot use FindName to find the Run
var anotherRunText = myTextBlock.Inlines.Where(x=> x.FindName
}
解决方法
如果您唯一区分Run
的方法是通过其文本。您确实可以使用已经尝试过的内容,但是可以使用text属性来代替Name
属性:
string FindInlineText(string keyword)
{
string anotherRunText = ((Run)myTextBlock.Inlines.First(i => ((Run)i).Text.Contains(keyword))).Text;
return anotherRunText;
}
似乎无法用另一种方法来实现,因为Run.Name
仅在后面的代码中获得,尽管Tag
属性应该从FrameworkContentElement
类继承,但是无法设置。
如果确实需要使用另一个标识符来区分文本元素,则可以考虑使用水平StackPanel
和多个TextBlock
:
StackPanel stack = new StackPanel { Orientation = Windows.UI.Xaml.Controls.Orientation.Horizontal };
for (int i = 0; i < 10; i++)
{
stack.Children.Add(new TextBlock
{
Name = $"inlineblock_{i}",Text = i.ToString()
});
}
现在您当然可以通过使用以下命令来获取正确的TextBlock
文本:
string certainText = ((TextBlock)stack.Children.First(i => ((TextBlock)i).Name == certainName)).Text;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。