首页 > 解决方案 > 如何在触发器的设置器中设置部分文本的前景?

问题描述

我需要在具有不同前景的按钮内写入部分文本。到目前为止,按照这个解决方案,我正在使用以下代码:

<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>

当然这不起作用,因为属性值被设置了不止一次。寻找解决方案我发现了这个。它基本上说使用多重绑定

<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>

但我不确定它是否适合我的情况,以及最终如何使用它。

标签: c#wpfxaml

解决方案


Runs 将被设置为TextBlock.Inlines只有 getter,没有 setter 的属性。所以你不能Run在 Style 中设置 s。

您可以使用两个TextBlock元素并绑定MyBooleanVisibility它们的属性:

<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");
    }
}

推荐阅读