c# - 如何在触发器的设置器中设置部分文本的前景?
问题描述
我需要在具有不同前景的按钮内写入部分文本。到目前为止,按照这个解决方案,我正在使用以下代码:
<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>
但我不确定它是否适合我的情况,以及最终如何使用它。
解决方案
Run
s 将被设置为TextBlock.Inlines
只有 getter,没有 setter 的属性。所以你不能Run
在 Style 中设置 s。
您可以使用两个TextBlock
元素并绑定MyBoolean
到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");
}
}
推荐阅读
- javascript - 如何在谷歌的操作中禁用列表中的项目选择?
- reactjs - React SVG不会在属性更新时重新渲染
- python - 每次访问时更改的模拟属性
- c++ - 如何使用字符串将无效操作数修复为二进制表达式?
- perl - 来自 CSV 文件的 Undef 值会产生不良结果
- android - 当我想用 epson TM T20 打印我的票时,我可以打印我的票,但异常状态 err_illegal 到 affich
- c# - 贝尔曼-福特负循环前身不存在
- c# - 如何使用 LINQ 在字典中查找元素
- php - SQL 查询在 PHP 中不起作用,没有数据插入数据库
- python - 从 Ruby 移植到 Python:如何处理“yield”