Группировка данных в FlipView в UWP C# - PullRequest
0 голосов
/ 27 февраля 2020

У меня есть json, который должен декодировать и отображать в формате flipview или скользящем формате. В моем json есть информация в том же разделе (с тем же идентификатором question_id), которая должна отображаться на одной странице во флипвью.

Проблема в том, что они отображаются по-разному или независимо на разных страницах, но я хочу, чтобы те, у кого одинаковый идентификатор, отображались вместе на одной странице

{
"total_questions": 3,
"as_id": "01401d9ec09a54b1db426462399c22f5",
"as_type": "assessment",
"as_title": "Structured test",
"as_no_sec_a": "3",
"as_no_sec_b": "0",
"duration": "00:20",
"subject": "11eaa833d04bde3362fa3ff6d7a96188",
"term": "84d2b094491c900cc455fe47709a5833",
"class": "ab904f3e0be607d7c29612a89b59d3e8",
"questions": [
    {
        "question_section": "b",
        "question_id": "55f0495109febf1d55f058a6d882a2b8",
        "question_type": "structured",
        "question_form": "short",
        "question_image": "",
        "question": "<p><span style=\"font-family:Lato;font-size:22px;\">Friction</span></p>",
        "question_instruction": "",
        "sections": [
            {
                "section_id": "2d15cc79ecd65beee2ab2bc74110fa12",
                "question_id": "55f0495109febf1d55f058a6d882a2b8",
                "section_type": "structured",
                "section_sub_type": "long",
                "section_question": "<p><span style=\"font-family:Lato;font-size:22px;\">What is friction</span></p>",
                "section_image": "",
                "section_instruction": "<p><span style=\"font-family:Lato;font-size:22px;\">Answer</span></p>"
            }
        ]
    },
    {
        "question_section": "a",
        "question_id": "2df3c9d9b5d9d85dd31ae39ff2aeda4b",
        "question_type": "structured",
        "question_form": "long",
        "question_image": "",
        "question": "<p><span style=\"font-family:Lato;font-size:22px;\">What is the importance of including calcium in chicken feed?</span></p>",
        "question_instruction": "<p><span style=\"font-family:Lato;font-size:22px;\">type your answer below</span></p>"
    },
    {
        "question_section": "a",
        "question_id": "1d02f11bbfb6741edb345b66b8fb147d",
        "question_type": "structured",
        "question_form": "short",
        "question_image": "",
        "question": "<p><span style=\"font-size:22px;font-family:Lato;\">Give any one example of a root tuber</span></p>",
        "question_instruction": "<p><span style=\"font-size:22px;\">Type your answer below</span></p>"
    },
    {
        "question_section": "b",
        "question_id": "82a3ecbf3cbfebd30d9dfe17a0f3354c",
        "question_type": "structured",
        "question_form": "short",
        "question_image": "",
        "question": "<p><span style=\"font-family:Lato;font-size:22px;\">Gravity as a force</span></p>",
        "question_instruction": "",
        "sections": [
            {
                "section_id": "b08b9467da3d21820ec223d46e1ec780",
                "question_id": "82a3ecbf3cbfebd30d9dfe17a0f3354c",
                "section_type": "structured",
                "section_sub_type": "long",
                "section_question": "<p><span style=\"font-family:Lato;font-size:22px;\">Why is gravity very important</span></p>",
                "section_image": "",
                "section_instruction": "<p>Give what its use is</p>"
            },
            {
                "section_id": "85e9d5ad8e41863825651a110b901744",
                "question_id": "82a3ecbf3cbfebd30d9dfe17a0f3354c",
                "section_type": "structured",
                "section_sub_type": "",
                "section_question": "<p><span style=\"font-family:Lato;font-size:22px;\">Where does gravity not function</span></p>",
                "section_image": "",
                "section_instruction": "<p><span style=\"font-family:Lato;font-size:22px;\">Give where it does not</span></p>"
            }
        ]
    }
],
"success": 1,
"title": "Successful",
"message": "Questions fetched."

}

Я использую Newtonsoft. Json для декодирования

Ниже приведены изображения того, как мне нужно, чтобы моя информация отображалась в одном флипвью. Они расположены в соответствии с переворотами или страницами в перевернутом виде

Изображение первого переворота

Изображение второго переворота

Изображение третьего сальто

Изображение четвертого сальто

1 Ответ

0 голосов
/ 02 марта 2020

Проблема в том, что они отображаются по-разному или независимо на разных страницах, но я хочу, чтобы они имели одинаковый идентификатор.

Для ваших требований вы можете использовать текущую структуру json напрямую , и передайте поле сечений в ItemsControl, где в FilpView элемент управления DataTemplate. Пожалуйста, проверьте следующий код Xaml. И мы используем Microsoft.Toolkit (Expander) для оптимизации макета. И используйте CollectionVisibilityConverter для управления отображением Expander или не основываться на количестве секций.

<Page
   ......
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:converters="using:Microsoft.Toolkit.Uwp.UI.Converters"
   ......

<Page.Resources>
    <converters:CollectionVisibilityConverter
        x:Key="CollectionVisibilityConverter"
        EmptyValue="Collapsed"
        NotEmptyValue="Visible"
        />
</Page.Resources>

<Grid>
    <FlipView
        x:Name="MyFlipView"
        BorderBrush="Black"
        BorderThickness="1"
        >
        <FlipView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>
                    <StackPanel Grid.Row="0" Orientation="Vertical">
                        <TextBlock
                            x:Name="Qid"
                            Margin="10,0,0,0"
                            Text="{Binding question_id}"
                            />
                        <WebView
                            x:Name="Qcontnet"
                            Height="200"
                            Margin="10,10,0,0"
                            local:HtmlHelper.SourceString="{Binding question}"
                            />
                        <WebView
                            x:Name="Qinstruction"
                            Height="200"
                            Margin="10,10,0,0"
                            local:HtmlHelper.SourceString="{Binding question_instruction}"
                            />
                    </StackPanel>
                    <Grid Grid.Row="1" Visibility="{Binding sections, Converter={StaticResource CollectionVisibilityConverter}}">
                        <controls:Expander
                            x:Name="Expander1"
                            Margin="0,0,0,10"
                            VerticalAlignment="Top"
                            HorizontalContentAlignment="Stretch"
                            ExpandDirection="Down"
                            Header="Question Sections"
                            IsExpanded="False"
                            >
                            <ItemsControl ItemsSource="{Binding sections}">
                                <ItemsControl.ItemTemplate>
                                    <DataTemplate>
                                        <StackPanel Orientation="Vertical">
                                            <TextBlock Margin="10,10,0,0" Text="{Binding question_id}" />
                                            <WebView
                                                x:Name="SQcontnet"
                                                Height="44"
                                                Margin="10,10,0,0"
                                                local:HtmlHelper.SourceString="{Binding section_question}"
                                                />
                                            <WebView
                                                x:Name="SQinstruction"
                                                Height="44"
                                                Margin="10,10,0,0"
                                                local:HtmlHelper.SourceString="{Binding section_instruction}"
                                                />
                                        </StackPanel>

                                    </DataTemplate>
                                </ItemsControl.ItemTemplate>
                            </ItemsControl>
                        </controls:Expander>
                    </Grid>
                </Grid>
            </DataTemplate>
        </FlipView.ItemTemplate>
    </FlipView>

</Grid>

Код позади

public class HtmlHelper : DependencyObject
{
    public static readonly DependencyProperty SourceStringProperty = DependencyProperty.RegisterAttached("SourceString", typeof(string), typeof(HtmlHelper), new PropertyMetadata("", OnSourceStringChanged));

    public static string GetSourceString(DependencyObject obj)
    {
        return obj.GetValue(SourceStringProperty).ToString();
    }

    public static void SetSourceString(DependencyObject obj, string value)
    {
        obj.SetValue(SourceStringProperty, value);
    }

    private static void OnSourceStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        WebView wv = d as WebView;
        if (wv != null)
        {
            wv.NavigateToString(e.NewValue.ToString());
        }
    }
}

public sealed partial class MainPage : Page
{   
    public MainPage()
    {
        this.InitializeComponent();
        this.Loaded += MainPage_Loaded;
    }

    private async void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        LoadQuestions();

    }
    private async void LoadQuestions()
    {
        var file = await Package.Current.Installed­Location.GetFileAsync("JsonData.txt");
        if (file != null)
        {
            string JsonString = await Windows.Storage.FileIO.ReadTextAsync(file);
            Model m = JsonConvert.DeserializeObject<Model>(JsonString);
            MyFlipView.ItemsSource = m.questions;
        }
    }
}

Класс модели

public class Section
{
    public string section_id { get; set; }
    public string question_id { get; set; }
    public string section_type { get; set; }
    public string section_sub_type { get; set; }
    public string section_question { get; set; }
    public string section_image { get; set; }
    public string section_instruction { get; set; }
}

public class Question
{
    public string question_section { get; set; }
    public string question_id { get; set; }
    public string question_type { get; set; }
    public string question_form { get; set; }
    public string question_image { get; set; }
    public string question { get; set; }
    public string question_instruction { get; set; }
    public List<Section> sections { get; set; }
}

public class Model
{
    public int total_questions { get; set; }
    public string as_id { get; set; }
    public string as_type { get; set; }
    public string as_title { get; set; }
    public string as_no_sec_a { get; set; }
    public string as_no_sec_b { get; set; }
    public string duration { get; set; }
    public string subject { get; set; }
    public string term { get; set; }
    public string @class { get; set; }
    public List<Question> questions { get; set; }
    public int success { get; set; }
    public string title { get; set; }
    public string message { get; set; }
}
...