正如 xaml 和@BasBrekelmans 中的错误所说,您尝试将Run
元素分配给需要string
.
根据您的要求,只需使用 aMultiBinding
将StringFormat
您的绑定值格式化为所需的格式。
就像是:
<DataTrigger Binding="{common:ComparisonBinding DataContext.Discount,GT,0}"
Value="{x:Null}">
<Setter TargetName="price"
Property="Text">
<Setter.Value>
<MultiBinding StringFormat="Some Custom Formatted Text Value1: {0} and Value2: {1}">
<Binding Path="BindingValue1" />
<Binding Path="BindingValue2" />
</MultiBinding>
</Setter.Value>
</Setter>
</DataTrigger>
如果它是TextBlock
您尝试使用内联绑定来调整的视觉样式,那么您最好使用比单个元素更好的元素来修改控件的模板TextBlock
以允许这样做。
但是,您可以通过使用转换器并将您的应用DataTrigger.Setter
到TextBlock.Tag
像这样说:
public class TextBlockInlineFormatConverter : IMultiValueConverter {
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
if (values.Length < 3)
return null;
TextBlock textblock = values[0] as TextBlock;
if (textblock == null)
return null;
textblock.ClearValue(TextBlock.TextProperty);
textblock.Inlines.Add(new Run("Some text ") { Foreground = Brushes.Tomato });
textblock.Inlines.Add(new Run(values[1].ToString()) { Foreground = Brushes.Blue });
textblock.Inlines.Add(new Run(" and Some other text ") { Foreground = Brushes.Tomato });
textblock.Inlines.Add(new Run(values[2].ToString()) { Foreground = Brushes.Blue, FontWeight = FontWeights.Bold });
return textblock.Tag;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
和用法:
<DataTrigger Binding="{common:ComparisonBinding DataContext.Discount,GT,0}"
Value="{x:Null}">
<!-- Note the setter is on Tag and not Text since we modify the Text using Inlines within the converter -->
<Setter TargetName="price"
Property="Tag">
<Setter.Value>
<MultiBinding Converter="{StaticResource TextBlockInlineFormatConverter}"
Mode="OneWay">
<Binding Path="."
RelativeSource="{RelativeSource Self}" />
<Binding Path="BindingValue1" />
<Binding Path="BindingValue2" />
</MultiBinding>
</Setter.Value>
</Setter>
</DataTrigger>
仅当您被限制修改控件的模板时才使用解决方法。