教學課程:建立調適型配置Tutorial: Create adaptive layouts

本教學課程涵蓋使用 XAML 調適型配置功能的基本知識,可讓您建立在任何規模上看起來都很適宜的應用程式。This tutorial covers the basics of using XAML's adaptive layout features, which let you create apps that look good at any size. 您將了解如何新增視窗中斷點、建立新的 DataTemplate,以及如何使用 VisualStateManager 類別來量身打造應用程式的版面配置。You'll learn how to add window breakpoints, create a new DataTemplate, and use the VisualStateManager class tailor your app's layout. 您將使用這些工具,針對較小型的視窗大小最佳化影像編輯程式。You'll use these tools to optimize an image editing program for smaller window sizes.

影像編輯程式有兩個頁面。The image editing program has two pages. 「主頁面」 會顯示影像中心檢視,以及一些關於每個影像檔案的資訊。The main page displays a photo gallery view, along with some information about each image file.

Photolab 主頁面的螢幕擷取畫面。

「詳細資料頁面」 會在選取單一相片之後,顯示該相片。The details page displays a single photo after it has been selected. 飛出視窗編輯功能表可用來變更、重新命名和儲存相片。A flyout editing menu allows the photo to be altered, renamed, and saved.

Photolab 詳細頁面的螢幕擷取畫面。

必要條件Prerequisites

第 0 部分:從 github 取得起始程式碼Part 0: Get the starter code from github

針對此教學課程,您將從簡化版的 PhotoLab 範例開始著手。For this tutorial, you'll start with a simplified version of the PhotoLab sample.

  1. 移至 GitHub 範例頁面:https://github.com/Microsoft/Windows-appsample-photo-labGo to the GitHub page for the sample: https://github.com/Microsoft/Windows-appsample-photo-lab.

  2. 下一步,您將需要複製或下載範例。Next, you'll need to clone or download the sample. 按一下 [複製或下載] 按鈕。Click the Clone or download button. 子功能表會出現。A sub-menu appears. PhotoLab 範例的 GitHub 頁面上的複製或下載功能表The Clone or download menu on the PhotoLab sample's GitHub page

    如果您不熟悉 GitHub:If you're not familiar with GitHub:

    a.a. 按一下 [下載 ZIP] ,然後在本機儲存此檔案。Click Download ZIP and save the file locally. 這個下載的 .zip 檔案,包含您所需要的所有專案檔案。This downloads a .zip file that contains all the project files you need.

    b.b. 將檔案解壓縮。Extract the file. 使用 [檔案總管] 瀏覽至您下載的 .zip 檔案,以滑鼠右鍵按一下檔案,然後選取 [解壓縮全部...]。Use File Explorer to browse to the .zip file you just downloaded, right-click it, and select Extract All....

    c.c. 瀏覽至您範例的本機副本,並移至 Windows-appsample-photo-lab-master\xaml-basics-starting-points\adaptive-layout 目錄。Browse to your local copy of the sample and go the Windows-appsample-photo-lab-master\xaml-basics-starting-points\adaptive-layout directory.

    如果您熟悉 GitHub:If you are familiar with GitHub:

    a.a. 在本機複製存放庫中的主要分支。Clone the master branch of the repo locally.

    b.b. 瀏覽至 Windows-appsample-photo-lab\xaml-basics-starting-points\adaptive-layout 目錄。Browse to the Windows-appsample-photo-lab\xaml-basics-starting-points\adaptive-layout directory.

  3. 按兩下 Photolab.sln,在 Visual Studio 中開啟解決方案。Double-click Photolab.sln to open the solution in Visual Studio.

第 1 部分:定義視窗中斷點Part 1: Define window breakpoints

執行應用程式。Run the app. 這在全螢幕上看起來很不錯,但當您將視窗縮得太小時,使用者介面 (UI) 就不是那麼理想了。It looks good at full screen, but the user interface (UI) isn't ideal when you shrink the window too small. 您可以使用 VisualStateManager 類別,讓 UI 隨著不同視窗大小進行調整,以確保在外觀和風格上始終有良好的使用者體驗。You can ensure that the end-user experience always looks and feels right by using the VisualStateManager class to adapt the UI to different window sizes.

小型視窗:之前

如需有關應用程式版面配置的詳細資訊,請參閱文件的<版面配置>一節。For more info about app layout, see the Layout section of the docs.

新增視窗中斷點Add window breakpoints

第一個步驟是定義套用不同視覺狀態的「中斷點」。The first step is to define the breakpoints at which different visual states are applied. 如需小型、中型和大型螢幕中斷點的詳細資訊,請參閱螢幕大小和中斷點See Screen sizes and breakpoints for more information about the breakpoints for small, medium, and large screens.

從方案總管開啟 App.xaml,然後將下列程式碼加到 MergedDictionaries 後面,但在結尾的 </ResourceDictionary> 標記之前。Open App.xaml from the Solution Explorer, and add the following code after the MergedDictionaries, right before the closing </ResourceDictionary> tag.

    <!--  Window width adaptive breakpoints.  -->
    <x:Double x:Key="MinWindowBreakpoint">0</x:Double>
    <x:Double x:Key="MediumWindowBreakpoint">641</x:Double>
    <x:Double x:Key="LargeWindowBreakpoint">1008</x:Double>

這會建立 3 個中斷點,可讓您建立 3 個視窗大小範圍的新視覺狀態:This creates 3 breakpoints, which lets you create new visual states for 3 ranges of window sizes:

  • 小型 (0 - 640 像素寬度)Small (0 - 640 pixels wide)
  • 中型 (641 - 1007 像素寬度)Medium (641 - 1007 pixels wide)
  • 大型 (> 1007 像素寬度)Large (> 1007 pixels wide)

在此範例中,您只會針對小型視窗大小建立新的外觀。In this example, you create a new look only for the small window size. 中型和大型的大小會使用相同的外觀。The medium and large sizes use the same look.

第 2 部分:新增小型視窗大小的資料範本Part 2: Add a data template for small window sizes

若要讓此應用程式即使在小型視窗中顯示時,仍有不錯的外觀,您可以建立新的資料範本,以最佳化使用者縮小視窗時,影像庫檢視中的影像顯示方式。To make this app look good even when it's shown in a small window, you can create a new data template that optimizes how the images in the image gallery view are shown when the user shrinks the window.

建立新的 DataTemplateCreate a new DataTemplate

從 [方案總管] 開啟 MainPage.xaml,然後在 Page.Resources 標籤之內新增下列程式碼。Open MainPage.xaml from the Solution Explorer, and add the following code within the Page.Resources tags.

<DataTemplate x:Key="ImageGridView_SmallItemTemplate"
              x:DataType="local:ImageFileInfo">

    <!-- Create image grid -->
    <Grid Height="{Binding ItemSize, ElementName=page}"
          Width="{Binding ItemSize, ElementName=page}">

        <!-- Place image in grid, stretching it to fill the pane-->
        <Image x:Name="ItemImage"
               Source="{x:Bind ImageSource, Mode=OneWay}"
               Stretch="UniformToFill">
        </Image>

    </Grid>
</DataTemplate>

這個圖庫範本藉由消除影像周圍框線,以及移除每個縮圖下面的影像中繼資料 (檔案名稱、評分等等),節省螢幕實際可用空間。This gallery template saves screen real estate by eliminating the border around images, and getting rid of the image metadata (filename, ratings, and so on.) below each thumbnail. 但您不這麼做,而是將每個縮圖顯示為簡單的正方塊。Instead, you show each thumbnail as a simple square.

將中繼資料新增至工具提示Add metadata to a tooltip

您仍然希望使用者能夠存取每個影像的中繼資料,因此將工具提示新增至每個影像項目。You still want the user to be able to access the metadata for each image, so add a tooltip to each image item. 在您剛建立的 DataTemplate 的Image 標籤內新增下列程式碼。Add the following code within the Image tags of the DataTemplate you just created.

    <!-- Add a tooltip to the image that displays metadata -->
    <ToolTipService.ToolTip>
        <ToolTip x:Name="tooltip">

            <!-- Arrange tooltip elements vertically -->
            <StackPanel Orientation="Vertical"
                        Grid.Row="1">

                <!-- Image title -->
                <TextBlock Text="{x:Bind ImageTitle, Mode=OneWay}"
                           HorizontalAlignment="Center"
                           Style="{StaticResource SubtitleTextBlockStyle}" />

                <!-- Arrange elements horizontally -->
                <StackPanel Orientation="Horizontal"
                            HorizontalAlignment="Center">

                    <!-- Image file type -->
                    <TextBlock Text="{x:Bind ImageFileType}"
                               HorizontalAlignment="Center"
                               Style="{StaticResource CaptionTextBlockStyle}" />

                    <!-- Image dimensions -->
                    <TextBlock Text="{x:Bind ImageDimensions}"
                               HorizontalAlignment="Center"
                               Style="{StaticResource CaptionTextBlockStyle}"
                               Margin="8,0,0,0" />
                </StackPanel>
            </StackPanel>
        </ToolTip>
    </ToolTipService.ToolTip>

這樣就會在您將滑鼠游標暫留在縮圖 (或按住觸控螢幕) 時,顯示影像的標題、檔案類型及尺寸。This will show the title, file type, and dimensions of an image when you hover the mouse over the thumbnail (or press and hold on a touch screen).

第 3 部分:定義視覺狀態Part 3: Define visual states

現已為您的資料建立新的版面配置,但應用程式目前並不知道何時要透過預設樣式使用這個版面配置。You've now created a new layout for your data, but the app currently has no way of knowing when to use this layout over the default styles. 若要修正此問題,您必須加入VisualStateManagerVisualState 定義。To fix this, you need to add a VisualStateManager and VisualState definitions.

加入 VisualStateManagerAdd a VisualStateManager

將下列程式碼新增至頁面的根元素 RelativePanelAdd the following code to the root element of the page, RelativePanel.

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup>
    ...

        <!-- Large window VisualState -->
        <VisualState>

        </VisualState>

        <!-- Medium window VisualState -->
        <VisualState>

        </VisualState>

        <!-- Small window VisualState -->
        <VisualState>

        </VisualState>

    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

建立 StateTriggers 以套用視覺狀態Create StateTriggers to apply the visual state

接下來,建立對應至每個貼齊點的 StateTriggersNext, create the StateTriggers that correspond to each snap point. 在 MainPage.xaml 中,將下列程式碼加入每個 VisualStateIn MainPage.xaml, add the following code to each VisualState.

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup>
    ...

        <!-- Large window VisualState -->
        <VisualState>

            <!-- Large window trigger -->
            <VisualState.StateTriggers>
                <AdaptiveTrigger MinWindowWidth="{StaticResource LargeWindowSnapPoint}"/>
            </VisualState.StateTriggers>

        </VisualState>

        <!-- Medium window VisualState -->
        <VisualState>

            <!-- Medium window trigger -->
            <VisualState.StateTriggers>
                <AdaptiveTrigger MinWindowWidth="{StaticResource MediumWindowSnapPoint}"/>
            </VisualState.StateTriggers>

        </VisualState>

        <!-- Small window VisualState -->
        <VisualState>

            <!-- Small window trigger -->
            <VisualState.StateTriggers >
                <AdaptiveTrigger MinWindowWidth="{StaticResource MinWindowSnapPoint}"/>
            </VisualState.StateTriggers>

        </VisualState>

    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

觸發每個視覺狀態時,應用程式就會使用指派給作用中 VisualState 的任何版面配置屬性。When each visual state is triggered, the app will use whatever layout attributes are assigned to the active VisualState.

設定每個視覺狀態的屬性Set properties for each visual state

最後,設定每個視覺狀態的屬性,以告知 VisualStateManager 狀態觸發時要套用哪些屬性。Finally, set properties for each visual state to tell the VisualStateManager what attributes to apply when the state is triggered. 每個 setter 都會以特定 XAML 元素的其中一個屬性為目標,並將該屬性設為指定值。Each setter targets one property of a particular XAML element and sets it to the given value. 將此程式碼新增至您剛才建立的 SmallWindow 視覺狀態 (在 StateTriggers 之後)。Add this code to the SmallWindow visual state you just created, after the StateTriggers.

    <!-- Small window setters -->
    <VisualState.Setters>

        <!-- Apply small template and styles -->
        <Setter Target="ImageGridView.ItemTemplate"
                Value="{StaticResource ImageGridView_SmallItemTemplate}" />
        <Setter Target="ImageGridView.ItemContainerStyle"
                Value="{StaticResource ImageGridView_SmallItemContainerStyle}" />

        <!-- Adjust the zoom slider to fit small windows-->
        <Setter Target="ZoomSlider.Minimum"
                Value="80" />
        <Setter Target="ZoomSlider.Maximum"
                Value="180" />
        <Setter Target="ZoomSlider.TickFrequency"
                Value="20" />
        <Setter Target="ZoomSlider.Value"
                Value="100" />
    </VisualState.Setters>

這些 setter 會將影像庫的 ItemTemplate 設定為您在上一節中建立的新 DataTemplateThese setters set the ItemTemplate of the image gallery to the new DataTemplate that you created in the previous section. 此外,也會調整縮放滑桿,使之更適合小型螢幕。They also tweak the zoom slider to better fit the small screen.

執行應用程式Run the app

執行應用程式。Run the app. 當應用程式載入時,嘗試變更視窗的大小。When the app loads, try changing the size of the window. 將視窗縮減成小型大小時,您應該會看到應用程式切換至您在第 2 部分建立的小型版面配置。When you shrink the window to a small size, you should see the app switch to the small layout you created in Part 2.

小型視窗:之後

更進一步Going further

現在完成了這個實習課程,您已具備充足的調整型配置知識,可以進一步自行實驗。Now that you've completed this lab, you have enough adaptive layout knowledge to experiment further on your own. 若要進行更大的挑戰,請嘗試最佳化較大螢幕大小的版面配置,例如 Surface Hub。For a bigger challenge, try optimizing the layout for larger screen sizes, like Surface Hub. 如果您想要測試 Surface Hub 版面配置,請參閱使用 Visual Studio 測試 Surface Hub 應用程式See Test Surface Hub apps using Visual Studio if you'd like to test a Surface Hub layout.

如果遇到困難,您可以在使用 XAML 回應式版面配置的下列各節中找到更多指引。If you get stuck, you can find more guidance in these sections of Responsive layouts with XAML.

或者,如果您想要深入了解最初的編輯相片應用程式是如何建置,請參閱 XAML 使用者介面資料繫結的那些教學課程。Alternatively, if you want to learn more about how the initial photo editing app was built, check out these tutorials on XAML user interfaces and data binding.

取得最終版本 PhotoLab 範例Get the final version of the PhotoLab sample

本教學課程不會建置到完整的編輯相片應用程式,因此請務必查看最終版本來了解各項功能,例如自訂動畫和樣式。This tutorial doesn't build up to the complete photo editing app, so be sure to check out the final version to see other features such as custom animations and styles.