WPF 样式设置器中的多个 Run 元素 [英] Multiple Run elements in WPF Style setter
问题描述
是否可以在 XAML
中在 Style
setter 中定义多个 Run
?
Is it possible in XAML
to define multiple Run
's inside a Style
setter?
以下定义了两个 Run
并失败:
The following has two Run
's defined and fails:
属性Value"设置了不止一次.
The property 'Value' is set more than once.
<TextBlock>
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Text">
<Setter.Value>
<Run Text="{Binding SelectedItem.iso}"/>
<Run Text="{Binding SelectedItem.value}"/>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedItem.type}" Value={x:Null}">
<Setter Property="Text" Value="No value" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
可以在保留使用多个 Run
的同时修复这个问题吗?
Can this be fixed while preserving the usage of multiple Run
's?
推荐答案
Setter 作用于一个属性,所以它只能有一个值,你得到的错误是合乎逻辑的:它无法理解你在尝试什么要做到这一点,它可以只是...将一个属性设置为给定的值.
A Setter works on one property, so it can have only one value, the error you get is logical: it has no way of understanding what you're trying to do, it can just... set a property to a given value.
所以这个想法是给它这个值,因为它应该是:附加文本.为此,您可以使用 MultiBinding,它接受多个值并将它们作为一个返回,具体取决于 StringFormat 你给它:
So the idea is to give it this value as it should be: appended texts. To do so, you would use MultiBinding, which takes multiple values and returns them as one, depending on the StringFormat you give it:
<Setter.Value>
<MultiBinding StringFormat="{}{0}{1}{2}"><!-- Format as you wish -->
<Binding Path="SelectedItem.iso"/>
<Binding Source="{x:Static System:Environment.NewLine}"/>
<Binding Path="SelectedItem.value"/>
</MultiBinding>
</Setter.Value>
关于 StringFormat 的注意事项:您必须在开始时使用 {}
来转义大括号,否则它会将它们视为标记扩展启动器.
Note on StringFormat: You have to use {}
at start to escape braces, else it would consider them as markup extension starters.
这篇关于WPF 样式设置器中的多个 Run 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!