在ContentView中声明转换器会导致空白的xamarin表单页面

时间:2017-05-22 18:23:51

标签: xaml xamarin xamarin.forms

我正在完成创建在Xamarin Forms App中的页面上使用的测试用户控件的过程。 我想将一个主题作为字符串传递到测试页面的控件中,然后根据一些不同的因素(如用户设置和应用程序设置)将其转换为颜色。 但是,只要我在ContentView中声明我的转换器,我的页面就会停止渲染,而我得到的只是一个空白页面!

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             x:Class="MyProject.UserControls.MyControl"
             xmlns:helpers="clr-namespace:MyProject.Converters"             >
    <ContentView.Resources>
        <helpers:StringToColourConverter x:Key="ColorConverter" />
    </ContentView.Resources>
    <ContentView.Content>
        <StackLayout x:Name="ControlRoot">
            <Label x:Name="PrimaryLabel" Text="{Binding PrimaryText}" />
            <Label x:Name="SecondaryLabel" Text="{Binding SecondaryText}" />
        </StackLayout>
    </ContentView.Content>
</ContentView>

如果我注释掉以下几行:

    

然后页面按预期呈现主要和次要标签。但如果它在那里(甚至没有使用!)那么页面是空白的,我没有错误。我知道转换器正在接收正确,因为VS2017在XML声明中为我自动完成命名空间,如果我键入<helpers:则自动完成名称StringToColourConverter,但我的转换器中的断点从未被命中,所以代码甚至没有跑。

关于什么在这里失败的任何想法?我是否必须在ContentView中以不同方式声明转换器?

编辑1 对于转换器,我已经将其剥离,以确保它不是代码问题(我希望!):

public class StringToColourConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Color.Red;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value.ToString();
        }
    }

由于

1 个答案:

答案 0 :(得分:4)

您是否按如下方式注册转换器?换句话说,您是否省略了示例的ResourceDictionary标记?据我所知,他们应该在那里。

<ContentView.Resources>
   <ResourceDictionary>
        <helpers:StringToColourConverter x:Key="ColorConverter" />
   </ResourceDictionary>
</ContentView.Resources>

此外,如果需要更频繁地注册此类转换器,您可以考虑在App.xaml中注册它,这样您就不必在任何需要的地方单独引用它。

<Application.Resources>
    <ResourceDictionary>  
        <helpers:StringToColourConverter x:Key="ColorConverter" />
    </ResourceDictionary>
</Application.Resources>