在 TextBlock 中隐藏 <Run /> 标签 - WPF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18171571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hide <Run /> tag in TextBlock - WPF
提问by Alamakanambra
I have textblock with 2 Runtags and one Linebreak:
我有带有 2 个Run标签和一个的文本块Linebreak:
<TextBlock>
<Run Text="TopText"/>
<LineBreak/>
<Run x:Name="bottomRun" Text="Bottom text"/>
</TextBlock>
I want to hide second Runtag in code behind. But there is no Visibleproperty... Why is it so?
What is the best solution how to hide only one Runtag?
我想Run在后面的代码中隐藏第二个标签。但是没有Visible财产……为什么会这样?如何仅隐藏一个Run标签的最佳解决方案是什么?
回答by Rohit Vats
Visibilityis the property in the UIElementclass which all UI controls derive from but Rundoesn't derive from it.
Visibility是UIElement所有 UI 控件派生自但Run不派生自它的类中的属性。
Best you can do is to set Textproperty to String.Emptyin code behind:
你能做的最好的事情是在后面的代码中设置Text属性String.Empty:
bottomRun.Text = String.Empty;
回答by msr
The TextBlock you've got is pretty small. When faced with a similar situation, I duplicated it and bound the Visiblity property on TextBlock.
您拥有的 TextBlock 非常小。当遇到类似的情况时,我复制了它并在 TextBlock 上绑定了 Visiblity 属性。
<TextBlock Visibility="{Binding Path=LicenseValid, Converter={StaticResource BooleanToVisibilityConverter}, ConverterParameter=false }">
<Run Text="TopText"/>
<LineBreak/>
<Run x:Name="bottomRun" Text="Bottom text"/>
</TextBlock>
<TextBlock Visibility="{Binding Path=LicenseValid, Converter={StaticResource BooleanToVisibilityConverter}, ConverterParameter=false }">
<Run Text="TopText"/>
<LineBreak/>
<Run x:Name="bottomRun" Text="Bottom text"/>
</TextBlock>
The converter is suitably declared, defined and takes an 'invert' parameter.
转换器被适当地声明、定义并采用“反转”参数。
回答by Matt Becker
I know the OP wanted to solve this using a single TextBlock with Runs in it, but I solved the problem with a Horizontally oriented StackPanel of TextBlocks. It's a heavier solution since there are more controls involved, but works.
我知道 OP 想使用一个带有 Runs 的 TextBlock 来解决这个问题,但我用一个水平方向的 TextBlocks StackPanel 解决了这个问题。这是一个更重的解决方案,因为涉及更多的控制,但有效。
回答by A. Morel
You can user Style Trigger with Binding :
您可以使用带绑定的样式触发器:
<Run>
<Run.Style>
<Style TargetType="Run">
<Setter Property="Text" Value="Bottom text"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=variable}" Value="{x:Null}">
<Setter Property="Text" Value=""/>
</DataTrigger>
</Style.Triggers>
</Style>
</Run.Style>
</Run>
回答by Simon_Weaver
Sometimes this is appropriate - but not ideal if you truly need the text to 'run' and you want to have an automatic linebreak in the inline element.
有时这是合适的 - 但如果您确实需要文本“运行”并且希望在内联元素中自动换行,则这并不理想。
<TextBlock>
<InlineUIElement><TextBlock Visibility="Collapsed" Text="TopText"/></InlineUIElement>
<LineBreak/>
<Run x:Name="bottomRun" Text="Bottom text"/>
</TextBlock>

