Как отобразить ContentView в CollectionView в Xamarin Forms - PullRequest
0 голосов
/ 16 июня 2020

Я пытаюсь использовать ObservableCollection элементов управления (ContentViews) в CollectionView. Коллекция ContentView в настоящее время создается и заполняется в ctor моей ContentPage. Затем я устанавливаю ItemSource CollectionView для свойства на странице, содержащей ObservableCollection. Моя проблема в том, что ContentView вообще не отображаются.

Вот код XAML из ContentPage:

    <ContentPage.Content>
        <StackLayout>
            <CollectionView ItemsSource="{Binding MyPolicies}">
                <CollectionView.Header>
                    <StackLayout BackgroundColor="LightGray">
                        <Label Margin="10,0,0,0"
                               Text="My Policies"
                               FontSize="Small"
                               FontAttributes="Bold" />
                    </StackLayout>
                </CollectionView.Header>
            </CollectionView>
        </StackLayout>
    </ContentPage.Content>

Вот код в конструкторе ContentPage, который создает ContentViews и добавляет их в коллекцию, привязанную к CollectionView:

    public partial class TestCollectionView : ContentPage
    {
        public ObservableCollection<ThreeLineThreeColumnCardView> MyPolicies { get; private set; } = null;

        public TestCollectionView()
        {
            IList<ThreeLineThreeColumnCardView> sourcePolicies = new List<ThreeLineThreeColumnCardView>();
            CreateMyPolicies(sourcePolicies);

            InitializeComponent();
        }

        private void CreateMyPolicies(IList<ThreeLineThreeColumnCardView> sourcePolicies)
        {
            //
            sourcePolicies.Add(new ThreeLineThreeColumnCardView());

            sourcePolicies.Add(new ThreeLineThreeColumnCardView());

            sourcePolicies.Add(new ThreeLineThreeColumnCardView());

            //
            MyPolicies = new ObservableCollection<ThreeLineThreeColumnCardView>(sourcePolicies);
        }
    }

Вот ContentView, который я использую. Вы заметите, что для него установлены значения по умолчанию:

<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="NGIC_XAML.Controls.CardViews.ThreeLineThreeColumnCardView">
    <Frame WidthRequest="342"
           BackgroundColor="#FFFFFF"
           BorderColor="LightGray"
           CornerRadius="5"
           HasShadow="False"
           Padding="8"
           VerticalOptions="Center"
           HorizontalOptions="Center">
        <Grid WidthRequest="311" Margin="15, 13, 16, 13">
            <Grid.RowDefinitions>
                <RowDefinition Height="20" />
                <RowDefinition Height="30" />
                <RowDefinition Height="20" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <Label Grid.Row="0" Grid.Column="0" 
                   Text="{Binding CardTitle, FallbackValue='R0C0'}"
                   FontAttributes="None"
                   FontSize="14"
                   TextColor="{Binding CardTitleColor, FallbackValue='#333333'}"
                   VerticalTextAlignment="Center"
                   HorizontalTextAlignment="Start" />
            <Label Grid.Row="0" Grid.Column="1" 
                   Text="{Binding CardAmount, FallbackValue='R0C1'}"
                   FontAttributes="Bold"
                   FontSize="16"
                   TextColor="{Binding CardAmountColor, FallbackValue='#53585B'}"
                   VerticalTextAlignment="Center"
                   HorizontalTextAlignment="End" />
            <Label Grid.Row="0" Grid.Column="2" 
                   Text="{Binding CardAmount, FallbackValue='R0C2'}"
                   FontAttributes="Bold"
                   FontSize="16"
                   TextColor="{Binding CardAmountColor, FallbackValue='#53585B'}"
                   VerticalTextAlignment="Center"
                   HorizontalTextAlignment="End" />

            <Label Grid.Row="1" Grid.Column="0"
                   Text="{Binding CardDate, FallbackValue='R1C0'}"
                   FontSize="12"
                   TextColor="{Binding CardDateColor, FallbackValue='#70777C'}"
                   VerticalTextAlignment="Center"
                   HorizontalTextAlignment="Start" />
            <Label Grid.Row="1" Grid.Column="1"
                   Text="{Binding CardComment, FallbackValue='R1C1'}"
                   FontSize="12"
                   TextColor="{Binding CardCommentColor, FallbackValue='#70777C'}"
                   VerticalTextAlignment="Center"
                   HorizontalTextAlignment="End" />
            <Label Grid.Row="1" Grid.Column="2"
                   Text="{Binding CardComment, FallbackValue='R1C2'}"
                   FontSize="12"
                   TextColor="{Binding CardCommentColor, FallbackValue='#70777C'}"
                   VerticalTextAlignment="Center"
                   HorizontalTextAlignment="End" />

            <Label Grid.Row="2" Grid.Column="0"
                   Text="{Binding CardDate, FallbackValue='R2C0'}"
                   FontSize="12"
                   TextColor="{Binding CardDateColor, FallbackValue='#70777C'}"
                   VerticalTextAlignment="Center"
                   HorizontalTextAlignment="Start" />
            <Label Grid.Row="2" Grid.Column="1"
                   Text="{Binding CardComment, FallbackValue='R2C1'}"
                   FontSize="12"
                   TextColor="{Binding CardCommentColor, FallbackValue='#70777C'}"
                   VerticalTextAlignment="Center"
                   HorizontalTextAlignment="End" />
            <Label Grid.Row="2" Grid.Column="2"
                   Text="{Binding CardComment, FallbackValue='R2C2'}"
                   FontSize="12"
                   TextColor="{Binding CardCommentColor, FallbackValue='#70777C'}"
                   VerticalTextAlignment="Center"
                   HorizontalTextAlignment="End" />
        </Grid>
    </Frame>
</ContentView>

И вот как ContentView выглядит в исходном состоянии:

raw card view

Итак, у меня вопрос: как мне получить коллекцию «карточек» для отображения в CollectionView на моей ContentPage?

UPDATE Добавлено в ContentPage:

                    <DataTemplate>
                        <Grid Padding="10">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <cards:ThreeLineCardView />
                        </Grid>
                    </DataTemplate>
                </CollectionView.ItemTemplate>

UPADTE Продемонстрируйте, что предварительно заполненная карточка (ContentView) может отображаться в сетке за пределами CollectionView

    <ContentPage.Content>
        <StackLayout>
            <!--<CollectionView ItemsSource="{Binding MyPolicies}">
                <CollectionView.Header>
                    <StackLayout BackgroundColor="LightGray">
                        <Label Margin="10,0,0,0"
                               Text="My Policies"
                               FontSize="Small"
                               FontAttributes="Bold" />
                    </StackLayout>
                </CollectionView.Header>
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <Grid Padding="10">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <cards:ThreeLineCardView />
                        </Grid>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>-->
            <Grid Padding="10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <cards:ThreeLineCardView />
            </Grid>
        </StackLayout>
    </ContentPage.Content>

enter image description here

1 Ответ

1 голос
/ 17 июня 2020

Я не уверен, что ты этого хочешь. Если нет, вы можете прокомментировать ниже.

Я создаю ContentView с именем CardView , код xaml совпадает с вашим общим.

Затем используется в Xaml of ContentPage следующим образом:

<CollectionView x:Name="collectionView"
                ItemsLayout="VerticalList">
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <appentrytest:CardView />
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

CardViewModel :

public class CardViewModle
{
    public string CardTitle { set; get; }
    public string CardAmount { set; get; }
    public string CardDate { set; get; }
    public string CardComment { set; get; }
}

In ContentPage , установить источник данных для CollectView:

public partial class PageFourth : ContentPage
{
    public List<CardViewModle> cardViewModles { set; get; }

    public PageFourth()
    {
        InitializeComponent();

        cardViewModles = new List<CardViewModle>();
        cardViewModles.Add(new CardViewModle() { CardTitle = "1", CardAmount = "2", CardComment = "one more", CardDate = "2020-06-17" });
        cardViewModles.Add(new CardViewModle() { CardTitle = "2", CardAmount = "5", CardComment = "two more", CardDate = "2020-06-17" });
        cardViewModles.Add(new CardViewModle() { CardTitle = "3", CardAmount = "6", CardComment = "three more", CardDate = "2020-06-17" });
        cardViewModles.Add(new CardViewModle() { CardTitle = "4", CardAmount = "8", CardComment = "four more", CardDate = "2020-06-17" });
        cardViewModles.Add(new CardViewModle() { CardTitle = "5", CardAmount = "12", CardComment = "five more", CardDate = "2020-06-17" });
        cardViewModles.Add(new CardViewModle() { CardTitle = "6", CardAmount = "18", CardComment = "six more", CardDate = "2020-06-17" });
        cardViewModles.Add(new CardViewModle() { CardTitle = "7", CardAmount = "80", CardComment = "seven more", CardDate = "2020-06-17" });
        cardViewModles.Add(new CardViewModle() { CardTitle = "8", CardAmount = "20", CardComment = "eight more", CardDate = "2020-06-17" });

        collectionView.ItemsSource = cardViewModles;

    }
}

Эффект:

enter image description here

==== ================== Обновление ===========================

Если вы хотите, чтобы каждый элемент CollectionView также мог содержать список элементов управления, вы можете использовать Bindable Layouts для этого.

The Xaml из CardView следующим образом:

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="AppEntryTest.CardView">
  <ContentView.Content>
        <Frame WidthRequest="342"
               BackgroundColor="#FFFFFF"
               BorderColor="LightGray"
               CornerRadius="5"
               HasShadow="False"
               Padding="8"
               VerticalOptions="Center"
               HorizontalOptions="Center">
            <Grid WidthRequest="311"
                  Margin="15, 13, 16, 13">
                <Grid.RowDefinitions>
                    <RowDefinition Height="20" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="40*" />
                    <ColumnDefinition Width="60*" />
                </Grid.ColumnDefinitions>
                <Label Grid.Row="0"
                       Grid.Column="0"
                       Text="{Binding CardTitle, FallbackValue='R0C0'}"
                       FontAttributes="None"
                       FontSize="14"
                       TextColor="{Binding CardTitleColor, FallbackValue='#333333'}"
                       VerticalTextAlignment="Center"
                       HorizontalTextAlignment="Start" />
                <Label Grid.Row="0"
                       Grid.Column="1"
                       Text="{Binding CardAmount, FallbackValue='R0C1'}"
                       FontAttributes="Bold"
                       FontSize="16"
                       TextColor="{Binding CardAmountColor, FallbackValue='#53585B'}"
                       VerticalTextAlignment="Center"
                       HorizontalTextAlignment="Center" />

                <StackLayout Grid.Row="1"
                            Grid.ColumnSpan="2"
                            Orientation="Vertical"
                            BindableLayout.ItemsSource="{Binding CommetList}">
                    <BindableLayout.ItemTemplate>
                        <DataTemplate>
                            <StackLayout Orientation="Horizontal">
                                <Label Grid.Column="0"
                                       Text="{Binding CardDate, FallbackValue='R1C0'}"
                                       FontSize="12"
                                       TextColor="{Binding CardDateColor, FallbackValue='#70777C'}"
                                       WidthRequest="300"
                                       VerticalTextAlignment="Center"
                                       HorizontalTextAlignment="Start" />
                                <Label Text="{Binding CardComment, FallbackValue='R1C1'}"
                                       FontSize="12"
                                       TextColor="{Binding CardCommentColor, FallbackValue='#70777C'}"
                                       WidthRequest="900"
                                       VerticalTextAlignment="Center"
                                       HorizontalTextAlignment="Center" />
                            </StackLayout>
                        </DataTemplate>
                    </BindableLayout.ItemTemplate>
                </StackLayout>
            </Grid>
        </Frame>
    </ContentView.Content>
</ContentView>

Также используется в ContentPage :

<ContentPage.Content>
    <StackLayout>
        <Label Text="Welcome to Xamarin.Forms!"
            VerticalOptions="CenterAndExpand" 
            HorizontalOptions="CenterAndExpand" />
        <CollectionView x:Name="collectionView"
                        ItemsLayout="VerticalList">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <appentrytest:CardView />
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </StackLayout>
</ContentPage.Content>

Здесь необходимо создать CardCommentModel :

public class CardCommentModel
{
    public string CardDate { set; get; }
    public string CardComment { set; get; }
}

И измените CardViewModle следующим образом:

public class CardViewModle
{
    public string CardTitle { set; get; }
    public string CardAmount { set; get; }

    public List<CardCommentModel> CommetList { set; get; }
}

Затем в ContenPage , установив данные для CollectView :

public partial class PageFourth : ContentPage
{
    public List<CardViewModle> cardViewModles { set; get; }

    public PageFourth()
    {
        InitializeComponent();

        List<CardCommentModel> cardCommentModelsOne = new List<CardCommentModel>();
        cardCommentModelsOne.Add(new CardCommentModel() { CardDate = "13:12:16", CardComment = "comment one" });
        cardCommentModelsOne.Add(new CardCommentModel() { CardDate = "13:15:16", CardComment = "comment two" });

        List<CardCommentModel> cardCommentModelsTwo = new List<CardCommentModel>();
        cardCommentModelsTwo.Add(new CardCommentModel() { CardDate = "14:12:16", CardComment = "comment one" });
        cardCommentModelsTwo.Add(new CardCommentModel() { CardDate = "15:22:16", CardComment = "comment two" });
        cardCommentModelsTwo.Add(new CardCommentModel() { CardDate = "15:42:16", CardComment = "comment three" });

        List<CardCommentModel> cardCommentModelsThree = new List<CardCommentModel>();
        cardCommentModelsThree.Add(new CardCommentModel() { CardDate = "15:32:16", CardComment = "comment one" });
        cardCommentModelsThree.Add(new CardCommentModel() { CardDate = "15:29:11", CardComment = "comment two" });
        cardCommentModelsThree.Add(new CardCommentModel() { CardDate = "16:12:16", CardComment = "comment three" });
        cardCommentModelsThree.Add(new CardCommentModel() { CardDate = "17:28:19", CardComment = "comment four" });
        cardCommentModelsThree.Add(new CardCommentModel() { CardDate = "18:42:26", CardComment = "comment five" });

        cardViewModles = new List<CardViewModle>();
        cardViewModles.Add(new CardViewModle() { CardTitle = "First Title", CardAmount = "Count : "+cardCommentModelsOne.Count.ToString(), CommetList= cardCommentModelsOne});
        cardViewModles.Add(new CardViewModle() { CardTitle = "Second Title", CardAmount = "Count : " + cardCommentModelsTwo.Count.ToString(), CommetList= cardCommentModelsTwo });
        cardViewModles.Add(new CardViewModle() { CardTitle = "Third Title", CardAmount = "Count : " + cardCommentModelsThree.Count.ToString(), CommetList= cardCommentModelsThree });

        collectionView.ItemsSource = cardViewModles;

    }
}

Эффект:

enter image description here

...