微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将特定的Run添加到Windows.UI.Xaml.Controls.TextBlock后,如何以编程方式访问它?

如何解决将特定的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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?