读取使用内联填充的 C# Textblock 文本属性 [英] Read C# Textblock Text Property filled using Inlines
问题描述
假设我有一个空的文本块:
Let us say that I have an empty Textblock :
textblock1.Text = "";
然后我只用这两个语句将内联内容放入其中:
Then I only put Inlines content in it with these two statements:
textblock1.Inlines.Add(new Run() { Text = "A. ", Foreground = Brushes.Red });
textblock1.Inlines.Add(new Run() { Text = responses.Current.Value, Foreground = Brushes.Black});
令人惊奇的是,我可以在我的窗口中正确地可视化内容,但是 Textblock 的 Text 属性一直为空!这会导致问题,因为我需要将此 Textblock 的值传递给另一个 Textblock.
The amazing stuff is that I can visualize the content properly in my window, however the Text property of the Textblock keeps being empty! This causes a problem because I need to pass the value of this Textblock to an other Textblock.
另一件我真的想不通的是,当我第二次调用我的函数时,textblock1.Text 属性正在正确更新!每次调用都会正确更新,但第一个调用!我在 msdn 上花了几个小时,但我真的很困惑.此外,我可以在网站上阅读:
The other thing I really can't figure out is that when I call my function for second time, the textblock1.Text property is being updated properly ! It is updated properly for every call but the first ! I've spent hours on msdn but I'm really confused. Moreover, I can read that on the website :
Text 属性返回一个值(InlineCollection 中所有 Run 元素的附加文本).但是,返回的值不包括已应用于 Run 元素的任何格式.
The Text property returns a value (the appended text of all Run elements in the InlineCollection). However, the returned value does not include any formatting that has been applied to the Run elements.
我已经非常仔细地检查了我的代码并进行了调试,以查看是否还有其他任何地方可以操作这些属性,但我还没有找到.如果有人有任何想法,对我来说这件事变得毫无意义......
I have very carefully checked my code and debugged to see if there were any other place where I manipulate these property, but I haven't found one. If anyone has any idea, to me this thing is becoming senseless...
推荐答案
只是为了详细说明我的评论以赋予一些意义,
Just to elaborate on my comment to give some meaning,
来自 MSDN 文档
加载意味着包含元素的逻辑树是完整的
Loaded entails that the logical tree that an element is contained within is complete
这对我们有帮助,因为这里的绑定引用了另一个 TextBlock
元素.绑定还取决于 DataContext
以及与特定 Binding
相关的其他一些因素,但通常它们会在 UI 加载后进行评估,这是有充分理由的.
which helps us since the binding here has a reference to the other TextBlock
element. Bindings also depend on DataContext
and few other factors relative to the specific Binding
but in general they get evaluated after the UI Loads for good reason.
因此在 UI 加载后设置源 TextBlock
的 Text
会导致一切正常,因为 Binding
在那时处于活动状态.
Hence setting the Text
of the source TextBlock
once the UI loads results in everything working fine since Binding
's are active at that point.
这篇关于读取使用内联填充的 C# Textblock 文本属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!