0
我一直在試圖實現一個簡單的值轉換器我只是不知道爲什麼StringFormat沒有被應用。正值變爲綠色,負值變爲紅色,但不是得到預期結果(+15.74),最終得出:15.74747474。價值轉換器不適用所需的字符串格式
我該如何得到這個工作?有人能給我一個我需要改變的想法嗎?
XAML
<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>
視圖模型
namespace My.ViewModel
{
public class LocationViewModel : UserControl, INotifyPropertyChanged
{
public MyViewModel()
{
SetActualValue();
}
public DateTime mDate = DateTime.Now;
public DateTime MDate
{
get { return mDate; }
set
{
if (value == mDate)
{
return;
}
else
{
mDate = value;
OnPropertyChanged("MDate");
SetActualValue();
}
}
}
double _actualValue;
public double ActualValue
{
get { return _actualValue; }
set
{
_actualValue = value;
OnPropertyChanged("ActualValue");
}
}
ValueConverter
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();
}
}
謝謝克萊門斯這麼清楚地解釋這一點。現在我知道發生了什麼。如果我從TextBlock中移除綁定,並將其保留,如下所示:( )我沒有任何值顯示。我錯過了什麼? –
iCosmin