【问题标题】:How to align labels differently in listview如何在列表视图中以不同方式对齐标签
【发布时间】:2021-06-24 03:46:39
【问题描述】:

ListView 中有 2 个标签。 第一个标签是ItemName(垂直对齐开始), 第二个标签是ItemDescription(垂直对齐到结尾)。

我想要实现的是... 当ItemDescription 为空时,我希望ItemName 垂直居中对齐

由于我是新人,如果你也能举个例子就好了。

这是我的 Xaml (ItemsPage)

<ContentPage.Content>
    <StackLayout>
        <ListView ItemsSource="{Binding _items, Mode=TwoWay}" x:Name="lstView" SelectedItem="{Binding SelectedItem}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid Padding="0,0,8,0" Margin="3,0,3,0">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="7*"/>
                            </Grid.ColumnDefinitions>

                        <Image Source="{Binding ImageUrl}" Grid.Column="0" Margin="3"></Image>

                        <Label Text="{Binding ItemName}" MaxLines="1" LineBreakMode="TailTruncation" FontSize="Medium" FontAttributes="Bold"></Label>

                        <Label Text="{Binding ItemDescription}" MaxLines="1" LineBreakMode="TailTruncation" Grid.Column="1" VerticalTextAlignment="End"></Label>
                
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage.Content>

【问题讨论】:

    标签: c# xaml listview xamarin.forms label


    【解决方案1】:

    您可以使用 IValueConverter

    https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/converters

    <Label Text="{Binding ItemName}" MaxLines="1" LineBreakMode="TailTruncation" FontSize="Medium" FontAttributes="Bold" VerticalTextAlignment="{Binding ItemDescription,Converter={StaticResource checkItemDescription}}"></Label>
    

    转换器

    public class AlignmentConverter : IValueConverter
    {
            public object Convert(object value, Type targetType, object parameter, 
        CultureInfo culture)
        {
            if(value==null)
                return LayoutOptions.Start;
    
            return LayoutOptions.End; 
    
        }
    
            public object ConvertBack(object value, Type targetType, object parameter, 
        CultureInfo culture)
        {
              throw new NotImplementedException();
        }
    }
    

    【讨论】:

    • 非常感谢,您的回复真的很有帮助。我真的很感激。我唯一改变的是TextAlignment 而不是LayoutOptions(我不知道它是否真的很重要)并且它工作得很好。再次感谢您
    • 恭喜@Noah!很高兴听到这个消息!
    猜你喜欢
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    相关资源
    最近更新 更多