C# 值转换器未应用所需的字符串格式
我一直在尝试实现一个简单的值转换器,但我不明白为什么没有应用StringFormat。正值变为绿色,负值变为红色,但不是得到所需的结果(+15.74),而是得到:15.7474 我怎样才能让它工作?有人能告诉我需要改变什么吗 XAMLC# 值转换器未应用所需的字符串格式,c#,wpf,ivalueconverter,C#,Wpf,Ivalueconverter,我一直在尝试实现一个简单的值转换器,但我不明白为什么没有应用StringFormat。正值变为绿色,负值变为红色,但不是得到所需的结果(+15.74),而是得到:15.7474 我怎样才能让它工作?有人能告诉我需要改变什么吗 XAML <Window.Resources> <local:PositiveConverter x:Key="PositiveConverter"/> <Style TargetType="TextBlock" x:Key
<Window.Resources>
<local:PositiveConverter x:Key="PositiveConverter"/>
<Style TargetType="TextBlock" x:Key="NumericTextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}, Converter={StaticResource PositiveConverter}}" Value="True">
<Setter Property="Foreground" Value="Green"/>
<Setter Property="Text" Value="{Binding StringFormat='({0:+0.0})'}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}, Converter={StaticResource PositiveConverter}}" Value="False">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="Text" Value="{Binding StringFormat='({0:-0.0})'}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<TextBlock Text="{Binding ActualValue}" Style="{StaticResource NumericTextBlock}"/>
</StackPanel>
</Grid>
值转换器
public class PositiveConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var number = 0.0;
var isNumber = double.TryParse(value.ToString(), out number);
return isNumber && number >= 0.0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
背景
Text="{Binding ActualValue}"
直接在TextBlock上具有比样式设置器更高的
<Setter Property="Text" Value="{Binding StringFormat='({0:+0.0})'}"/>
并从文本块中删除Text=“{Binding ActualValue}”
。设置
Text="{Binding ActualValue}"
直接在TextBlock上具有比样式设置器更高的
<Setter Property="Text" Value="{Binding StringFormat='({0:+0.0})'}"/>
并从文本块中删除
Text=“{Binding ActualValue}”
。感谢克莱门斯如此清楚地解释了这一点。现在我知道发生了什么事。如果我从TextBlock中删除绑定并保持如下状态:()我不会得到任何要显示的值。我遗漏了什么?谢谢你,克莱门斯,解释得这么清楚。现在我知道发生了什么事。如果我从TextBlock中删除绑定并保持如下状态:()我不会得到任何要显示的值。我错过了什么?