为前景创建转换器

时间:2012-05-18 09:09:20

标签: windows-phone-7 silverlight-4.0

我创建了一个转换器来将前景绑定到一个特殊值并更改它,但它总是将val作为null:

public class PositionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //string vall;
        //TextBlock txt= TextBlock.TextProperty(

        var val = value as TextBlock;
        if (val != null)
        {
            if (val.Text.StartsWith("-"))
            {
                return new SolidColorBrush(Colors.Red);

            }
            else
            {
                return new SolidColorBrush(Colors.Green);
            }
        }
        return new SolidColorBrush(Colors.Red);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
           <TextBlock FontSize="28"  x:Name="solde" TextWrapping="Wrap"  >
           <Run Text="        Solde : " Foreground="Black"/>
           <Run Text="{Binding amount}" Foreground="{Binding amount, Converter=               {StaticResource PositionConverter}}" Language="fr-FR"/>
             </TextBlock>

1 个答案:

答案 0 :(得分:1)

value是绑定所涉及的值(在您的情况下:金额),而不是控件。因此,将其强制转换为TextBlock将无法正常工作。

你可以试试这个:

public class PositionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {          
        if (value == null)
        {
            return new SolidColorBrush(Colors.Red);
        }

        if (value.ToString().StartsWith("-"))
        {
            return new SolidColorBrush(Colors.Red);                   
        }

        return new SolidColorBrush(Colors.Green);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}