首页 > 解决方案 > 如何为多个转换编写 Iconverter

问题描述

下面是我用来在绑定到列表视图之前转换值的代码。但是这里只有前 2 个转换工作,convert3 和 convert4 的结果没有显示。请帮助我

 <ContentPage.Resources>
        <local:Class1 x:Key="_converter"/>
    </ContentPage.Resources>

    <ContentPage.Content>
        <ListView x:Name="Models">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout>
                            <Label  Text="{Binding from_time,Converter={StaticResource _converter}}"/>
                            <Label  Text="{Binding to_time,Converter={StaticResource _converter}}"/>
                            <Label Text="{Binding from_time_tuesday,Converter={StaticResource _converter}}" TextColor="Brown"/>
                            <Label Text="{Binding to_time_tuesday,Converter={StaticResource _converter}}" TextColor="Brown"/>

                        </StackLayout>
                        
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>



public class Class1: IValueConverter
    {
        public  object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var str = (string)value; // value is the binding data
            if (str== "00:00:00.0000000")
                return "";
            return value;
        }
       
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

标签: c#xamarincross-platform

解决方案


由于它适用于第一个和第二个标签,我认为问题是由布局引起的。在您的情况下,StackLayout在运行时不会影响其子元素的大小。

你可以使用Grid

<Grid>
        <Grid.RowDefinitions>

            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />

        </Grid.RowDefinitions>

        <Label Grid.Row="0" HeightRequest="30"  Text="{Binding from_time,Converter={StaticResource _converter}}"/>
        <Label Grid.Row="1" HeightRequest="30"  Text="{Binding to_time,Converter={StaticResource _converter}}"/>
        <Label Grid.Row="2" HeightRequest="30" Text="{Binding from_time_tuesday,Converter={StaticResource _converter}}" TextColor="Brown"/>
        <Label Grid.Row="3" HeightRequest="30" Text="{Binding to_time_tuesday,Converter={StaticResource _converter}}" TextColor="Brown"/>

</Grid>

推荐阅读