UWP Настройка макета / положения элемента управления на основе размера экрана - PullRequest
0 голосов
/ 31 августа 2018

В настоящее время я создал очень грубый пользовательский интерфейс, который содержит NavigationView и ItemsControl, который отображает информацию из класса UserData.

Я изучаю способы реализации динамического интерфейса, который изменяет размер содержимого кадра в зависимости от размера окна. В настоящее время я выбрал в качестве выбора дизайна для Навигационного представления значение Minimal и добавил Frame, содержащий ItemsControl. Когда я запускаю программу в не развернутом режиме, экран выглядит следующим образом:

enter image description here

Когда я максимизирую страницу, элемент управления отображается так, как задумано:

enter image description here

Я считаю, что это как-то связано с установленным полем, но я не уверен, как лучше реализовать динамическое движение элемента управления. Я полагаю, что в навигационном представлении все это предварительно запечено, поэтому оно перемещается с размером окна. Я хотел бы сделать что-то подобное, чтобы контроль изменял размеры. Что обычно будет лучшим способом сделать это. Я видел, как VisualStateTriggers упоминался несколько раз, и мне было интересно, если это наилучшая практика, чтобы попытаться реализовать. Мне кажется, что мне нужно изменить размеры Frame, а не ItemsControl. Это тот случай?

Я бы хотел оставить интервал в 40 пикселей вокруг каждого края (кроме нижнего), чтобы контролировать визуальные эффекты.

Для тех, кому это нужно, вот текущий XAML для общего дизайна / макета:

<Page
    x:Class="BudgetSheet.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:mux="using:Windows.UI.Xaml.Controls"    

    xmlns:data="using:BudgetSheet.Data"   

    RequestedTheme="Dark">

    <Page.Resources>
        <data:UserDataCollection x:Key="userDataCollection"/>
    </Page.Resources>

    <Frame Background="{StaticResource CustomAcrylicDarkBackground}">

        <!-- Navigation view Variable decleration -->
        <mux:NavigationView IsSettingsVisible="False" 
                            PaneTitle=" Budget Sheet Menu "                            
                            x:Name="NavView"                             
                            IsBackButtonVisible="Collapsed" 
                            PaneDisplayMode="LeftMinimal" 
                            AlwaysShowHeader="True"        
                            SelectionChanged="NavView_SelectionChanged">

            <!-- All navigation view Items nested within here -->
            <mux:NavigationView.MenuItems>
                <StackPanel Orientation="Horizontal" UseLayoutRounding="False">
                    <AppBarButton Icon="Page2" Margin="0, 2, 1, 0" Tag="New_Sheet" HorizontalAlignment="Center" Width="56.5" Height="56.5" ClickMode="Press" Click="NewFile_ClickAsync"/>
                    <AppBarButton Icon="OpenFile" Margin="1, 2, 0, 0" Tag="Open_Sheet" HorizontalAlignment="Center" Width="56.5" Height="56.5" ClickMode="Press" Click="OpenFile_ClickAsync"/>
                    <AppBarButton Icon="Save" Margin="1, 2, 0, 0" Tag="Save_Sheet" HorizontalAlignment="Center" Width="56.5" Height="56.5" ClickMode="Press" Click="SaveButton_ClickAsync"/>
                    <AppBarButton Icon="Setting" Margin="1, 2, 0, 0" Tag="Settings_Page" HorizontalAlignment="Center" Width="56.5" Height="56.5" ClickMode="Press" Click="SettingsButton_Click"/>
                    <AppBarButton Icon="Calculator" Margin="1, 2, 0, 0" Tag="Calculator_Open" HorizontalAlignment="Center" Width="56.5" Height="56.5" ClickMode="Press" Click="CalcButton_ClickAsync"/>
                </StackPanel>

                <mux:NavigationViewItemSeparator/>
                <mux:NavigationViewItem Name="HomeItem" 
                                        Content="HOME" 
                                        Tag="HOME_Page" 
                                        FontSize="22" 
                                        HorizontalAlignment="Stretch" 
                                        FontWeight="Bold" 
                                        Foreground="#b880fc"/>
                <NavigationViewItemSeparator/>

                <mux:NavigationViewItem Name="OverviewItem" 
                                        Content="ACCOUNT OVERVIEW" 
                                        Tag="OverView_Page" 
                                        FontSize="22" 
                                        HorizontalAlignment="Stretch" 
                                        FontWeight="Bold" 
                                        Foreground="#b880fc"/>

                <mux:NavigationViewItem Name="BillsItem" 
                                        Content="BILLS" 
                                        Tag="Bills_Page" 
                                        FontSize="22" 
                                        HorizontalAlignment="Stretch" 
                                        FontWeight="Bold" 
                                        Foreground="#b880fc"/>

                <mux:NavigationViewItem Name="PeopleItem" 
                                        Content="BILL PAYERS" 
                                        Tag="BillPayer_Page" 
                                        FontSize="22" 
                                        HorizontalAlignment="Stretch" 
                                        FontWeight="Bold" 
                                        Foreground="#b880fc"/>

                <mux:NavigationViewItem Name="TransfersItem" 
                                        Content="BANK TRANSFERS" 
                                        Tag="Transfers_Page" 
                                        FontSize="22" 
                                        HorizontalAlignment="Stretch" 
                                        FontWeight="Bold" 
                                        Foreground="#b880fc"/>

                <mux:NavigationViewItem Name="PayDatesItem" 
                                        Content="PAY DATES" 
                                        Tag="PayDates_Page" 
                                        FontSize="22" 
                                        HorizontalAlignment="Stretch" 
                                        FontWeight="Bold" 
                                        Foreground="#b880fc"/>
            </mux:NavigationView.MenuItems>


            <!-- Defining the ContentFrame Transition effect-->
            <Frame x:Name="ContentFrame" HorizontalAlignment="Left" Width="1920" Margin="0,0,0,0" VerticalAlignment="Stretch">
                <Frame.ContentTransitions>
                    <TransitionCollection>
                        <NavigationThemeTransition/>
                    </TransitionCollection>
                </Frame.ContentTransitions>


                <!-- All information display is in here. This displays the "Accounts at a Glance" control-->
                <ItemsControl ItemsSource="{StaticResource userDataCollection}" Margin="40,40,40,727">

                    <!-- Changing Orientation of VirtualizingStackPanel -->
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel Orientation="Horizontal"/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>

                    <!-- Change header for ItemsControl -->
                    <ItemsControl.Template>
                        <ControlTemplate>
                            <Border Background="{StaticResource CustomAcrylicDarkBackground}">
                                <StackPanel>
                                    <TextBlock Text="Accounts At A Glance" FontSize="28" Foreground="#b880fc" Padding="12"/>
                                    <ItemsPresenter/>
                                </StackPanel>
                            </Border>
                        </ControlTemplate>
                    </ItemsControl.Template>


                    <!-- Design template for each card-->
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Grid Width="240" Height="240" Background="Gray" Margin="30,0,0,0" VerticalAlignment="Center" Padding="4">

                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition Height="*"/>
                                </Grid.RowDefinitions>

                                <TextBlock Grid.Row="0" Text="{Binding Name}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="24"/>
                                <TextBlock Grid.Row="1" Text="{Binding PayDate}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="14" />
                                <TextBlock Grid.Row="2" Text="{Binding NumberOfItems}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="14"/>
                            </Grid>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
                <!-- End of Frame Display-->
            </Frame>



            <NavigationView.PaneFooter>
                <Button x:Name="ChangeUser" Style="{StaticResource TextBlockButtonStyle}" Foreground="#b880fc" >
                    <StackPanel HorizontalAlignment="Stretch" Orientation="Horizontal">
                        <SymbolIcon Symbol="Contact" Margin="8"/>
                        <TextBlock VerticalAlignment="Center" HorizontalAlignment="Right">      
                                    Change User
                        </TextBlock>
                    </StackPanel>
                </Button>
            </NavigationView.PaneFooter>
        </mux:NavigationView>


    </Frame>
</Page>

Я прошу прощения за любые неудобства с этим

1 Ответ

0 голосов
/ 31 августа 2018

Прежде всего, вам не следует устанавливать ширину фрейма , удалите свойство width, и вам не нужно также устанавливать HorizontalAlignment или VerticalAlignment фрейма, потому что фрейм автоматически растягивается до доступного пространства.

вторая ошибка, которую вы совершаете, это установка диких полей в ItemsControl , ваша нижняя граница слишком высока. удалите поля и, если вы хотите получить маржу, просто установите Margin = "12" (это установит 12 полей на всех 4 сторонах).

Ошибка № 3 - установка Margin = "30,0,0,0" в сетку в вашем DataTemplate , чтобы поле оставалось равномерным по всем 3 сторонам, возможно, установлено Margin = "8" здесь.

И, наконец, я не знаю, почему вы используете ItemsControl, когда вы можете просто использовать GridView , который намного проще и проще в использовании?

Ниже приведен исправленный и уточненный более простой код для достижения того, чего вы пытаетесь достичь:

<!-- Defining the ContentFrame Transition effect-->
<Frame x:Name="ContentFrame">
    <Frame.ContentTransitions>
        <TransitionCollection>
            <NavigationThemeTransition/>
        </TransitionCollection>
    </Frame.ContentTransitions>


    <!-- All information display is in here. This displays the "Accounts at a Glance" control-->
    <GridView ItemsSource="{StaticResource userDataCollection}" Margin="12"
              Background="{StaticResource CustomAcrylicDarkBackground}">
        <GridView.Header>
            <TextBlock Text="Accounts At A Glance" FontSize="28" Foreground="#b880fc" Padding="12"/>
        </GridView.Header>

        <!-- Design template for each card-->
        <GridView.ItemTemplate>
            <DataTemplate>
                <Grid Width="240" Height="240" Background="Gray" Margin="12" Padding="4">

                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <!--you dont need this 4th row below because you have only 3 textblocks and this 4th row with * is causing your content to be pushed upwards within a gridviewitem.-->
                        <!--<RowDefinition Height="*"/>-->
                    </Grid.RowDefinitions>

                    <TextBlock Grid.Row="0" Text="{Binding Name}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="24"/>
                    <TextBlock Grid.Row="1" Text="{Binding PayDate}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="14" />
                    <TextBlock Grid.Row="2" Text="{Binding NumberOfItems}" HorizontalAlignment="Center" TextAlignment="Center" Width="220" FontSize="14"/>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
    <!-- End of Frame Display-->
</Frame>
...