我需要在具有不同前景的按钮内写入部分文本。到现在为止,关注this solution ,我使用了以下代码:
<Button>
<TextBlock Margin="20"
FontSize="24"
FontStyle="Normal"
FontWeight="Medium"
Foreground="#FF1384F5">
<Run>text1</Run>
<Run Foreground="#FF1372D3" Text="{Binding MyBinding}"/>
<Run >text2</Run>
</TextBlock>
</Button>
现在我需要根据触发器更改整个文本,因此我构建了一个如下所示的 DataTriger:
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding MyBoolean}" Value="True">
<Setter Property="Text">
<Setter.Value>
<Run>text1</Run>
<Run Foreground="#FF1372D3" Text="{Binding MyBinding}"/>
<Run >text2</Run>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding MyBoolean}" Value="False">
<Setter Property="Text" Value="text3" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
当然这是行不通的,因为属性值被设置了多次。寻找解决方案,我发现this 。它基本上说使用多重绑定(bind)
<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>
但我不确定它是否适合我的情况,以及最终如何使用它。
最佳答案
Run
将被设置为 TextBlock.Inlines
属性,该属性只有 getter,没有 setter。所以你不能在Style中设置Run
。
您可以使用两个 TextBlock
元素并将 MyBoolean
绑定(bind)到它们的 Visibility
属性:
<Grid>
<Grid.Resources>
<local:BoolToVisConverter x:Key="btoviscnv"/>
</Grid.Resources>
<TextBlock Text="text3" Visibility="{Binding MyBoolean, Converter={StaticResource btoviscnv}, ConverterParameter='not'}"/>
<TextBlock Visibility="{Binding MyBoolean, Converter={StaticResource btoviscnv}}">
<Run>text1</Run>
<Run Foreground="#FF1372D3" Text="{Binding MyBinding}"/>
<Run>text2</Run>
</TextBlock>
</Grid>
public class BoolToVisConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var bvalue = (bool)value;
if ((parameter as string)?.Equals("not") ?? false)
{
bvalue = !bvalue;
}
return bvalue ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException("It's one way converter");
}
}
关于c# - 如何在触发器的 setter 中设置部分文本的前景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54233029/