我可以申报多个转换器吗? WP8

Can I declare more than one converter? WP8

我正在使用 BooleanToVisibilityConvertor 来控制 ListBox DataTemplate 中 TextBlock 的可见性。

这是我的 XAML 代码:

    <phone:PhoneApplicationPage.Resources>
    <Converters:BooleanToVisibilityConvertor x:Key="booleanToVisibilityConvertor"/>
    </phone:PhoneApplicationPage.Resources>

    <TextBlock Grid.Row="2" HorizontalAlignment="Right" Padding="0,0,7,0" Visibility="{Binding AverageConsumption, Converter={StaticResource booleanToVisibilityConvertor}}"> 
     <Run Text="{Binding AverageConsumption}"/>
     <Run Text="l./100 km."/>
    </TextBlock>

以及后面的代码:

public class BooleanToVisibilityConvertor : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        {
            if (value != null)
            {
                if (!string.IsNullOrEmpty(value.ToString()))
                {
                    return Visibility.Visible;
                }

            }
            return Visibility.Collapsed;
        }
    }

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

这工作正常,但我需要一个(反向)转换器用于放置在同一位置的另一个 TextBlock (Grid.Row="2" Horizo​​ntalAlignment="Right") 使用 static Text="Partial Refueling" 因此当 {Binding AverageConsumption} 不为空或为空时,第一个 TextBlock 将可见,第二个将折叠,反之亦然。像这样:

    class BooleanToVisibilityConvertorReversed : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        {
            if (value != null)
            {
                if (!string.IsNullOrEmpty(value.ToString()))
                {
                    return Visibility.Collapsed;
                }
            }
            return Visibility.Visible;
        }
    }

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

我试图在 XAML 中声明另一个转换器:

    <phone:PhoneApplicationPage.Resources>
    <Converters:BooleanToVisibilityConvertor x:Key="booleanToVisibilityConvertor"/>
    <Converters:BooleanToVisibilityConvertorReversed x:Key="booleanToVisibilityConvertorReversed"/>
    </phone:PhoneApplicationPage.Resources>

但 InitializeComponent() 出现异常: ''System.Windows.Markup.XamlParseException' 类型的第一次机会异常发生在 System.Windows.ni.dll 中' 我该如何解决?

看来我发现了你的问题。你的 BooleanToVisibilityConvertorReversed class 不是 public。使其成为 public,您的问题应该消失了。