Style and design windows

Содержание
  1. Стиль приложений для Windows Style for Windows apps
  2. Цвет Color
  3. Оформление текста Typography
  4. Значки Icons
  5. Акрил Acrylic
  6. Эффект подсвечивания Reveal highlight
  7. Обозначение фокуса Reveal focus
  8. Звук Sound
  9. Стиль письма Writing style
  10. Стили XAML XAML styles
  11. Style for Windows apps
  12. Color
  13. Typography
  14. Icons
  15. Acrylic
  16. Reveal highlight
  17. Reveal focus
  18. Sound
  19. Writing style
  20. XAML styles
  21. Controls for Windows apps
  22. Intro
  23. Get the Windows UI Library
  24. Alphabetical index
  25. XAML Controls Gallery
  26. Additional controls
  27. Руководство: Создание пользовательских стилей Tutorial: Create custom styles
  28. Предварительные условия Prerequisites
  29. Часть 0. Получение начального кода на GitHub Part 0: Get the starter code from GitHub
  30. Часть 1. Создание необычного элемента управления ползунка Part 1: Create a fancy slider control
  31. Настройка элемента управления ползунка Customize a slider control
  32. Часть 2. Создание основных стилей Part 2: Create basic styles
  33. Создание стиля текстового блока со значением Create a value text block style
  34. Часть 3. Использование шаблона элемента управления для создания необычного ползунка Part 3: Use a control template to make a fancy slider

Стиль приложений для Windows Style for Windows apps

Стиль помогает выделить ваше приложение среди других. Рекомендации в этом разделе помогут создать стиль Fluent Design, используя цвет, шрифтовое оформление и новые функции, например акриловый материал и эффект отображения. Style is what makes your app stand out. The style guidelines in this section help you create a Fluent Design through color, typography, and new features such as acrylic material and reveal highlight.

Цвет Color

Цвета позволяют интуитивно ориентироваться среди различных информационных уровней приложения и служат важнейшим средством усиления модели взаимодействия. Color provides intuitive wayfinding through an app’s various levels of information and serves as a crucial tool for reinforcing the interaction model.

Оформление текста Typography

Основная цель шрифтового оформления как визуального представления языка — это ясность. As the visual representation of language, typography’s main task is to be clear. Стиль шрифтов никогда не должен затмевать эту цель. Its style should never get in the way of that goal. Следующие рекомендации посвящены использованию оформления для упрощения восприятия содержимого пользователями. The following guidelines focus on how to use typography to help users understand content easily.

Значки Icons

Хорошие значки согласуются со шрифтовым оформлением и языком проектирования в целом. Good icons harmonize with typography and with the rest of the design language. В них метафоры не смешиваются — они сообщают только то, что нужно, как можно скорее и проще. They don’t mix metaphors, and they communicate only what’s needed, as speedily and simply as possible.

Акрил Acrylic

Привнесите ощущение глубины с помощью акрила — кисти, позволяющей создавать потрясающие полупрозрачные поверхности. Create a sense of depth with acrylic, a brush that creates stunning, translucent surfaces.

Эффект подсвечивания Reveal highlight

Подсветите важные элементы. Use light to illuminate important elements.

Обозначение фокуса Reveal focus

Обозначение фокуса — это световой эффект для больших экранов, как в случае телевизора, используемого вместе с Xbox One. Этот эффект анимирует границу элементов для фокусировки. Reveal focus is a lighting effect for 10 foot experiences, such as Xbox One and television screens, and animates the border of focusable elements.

Звук Sound

Звук дополняет приложения и придает дополнительное преимущество в соответствии со стилем Windows на всех платформах. Sound helps complete an application’s user experience, and gives them that extra audio edge they need to match the feel of Windows across all platforms.

Стиль письма Writing style

Стиль письма может определить, станет ли приложение успешным или нет. Writing style can make a big difference between an awful user experience and a better one.

Стили XAML XAML styles

Платформа XAML предоставляет множество способов настройки внешнего вида приложений. You can customize the appearance of your apps in many ways by using the XAML framework. С помощью стилей вы можете настраивать свойства элементов управления и многократно использовать эти параметры, чтобы придать единообразный внешний вид нескольким элементам управления. Styles let you set control properties and reuse those settings for a consistent appearance across multiple controls.

Style for Windows apps

Style is what makes your app stand out. The style guidelines in this section help you create a Fluent Design through color, typography, and new features such as acrylic material and reveal highlight.

Color

Color provides intuitive wayfinding through an app’s various levels of information and serves as a crucial tool for reinforcing the interaction model.

Typography

As the visual representation of language, typography’s main task is to be clear. Its style should never get in the way of that goal. The following guidelines focus on how to use typography to help users understand content easily.

Icons

Good icons harmonize with typography and with the rest of the design language. They don’t mix metaphors, and they communicate only what’s needed, as speedily and simply as possible.

Acrylic

Create a sense of depth with acrylic, a brush that creates stunning, translucent surfaces.

Reveal highlight

Use light to illuminate important elements.

Reveal focus

Reveal focus is a lighting effect for 10 foot experiences, such as Xbox One and television screens, and animates the border of focusable elements.

Sound

Sound helps complete an application’s user experience, and gives them that extra audio edge they need to match the feel of Windows across all platforms.

Writing style

Writing style can make a big difference between an awful user experience and a better one.

XAML styles

You can customize the appearance of your apps in many ways by using the XAML framework. Styles let you set control properties and reuse those settings for a consistent appearance across multiple controls.

Controls for Windows apps

In Windows app development, a control is a UI element that displays content or enables interaction. Controls are the building blocks of the user interface. A pattern is a recipe for combining several controls to make something new.

We provide 45+ controls for you to use, ranging from simple buttons to powerful data controls like the grid view. These controls are a part of the Fluent Design System and can help you create a bold, scalable UI that looks great on all devices and screen sizes.

The articles in this section provide design guidance and coding instructions for adding controls & patterns to your Windows app.

Intro

General instructions and code examples for adding and styling controls in XAML and C#.

Add controls and handle events
There are 3 key steps to adding controls to your app: Add a control to your app UI, set properties on the control, and add code to the control’s event handlers so that it does something.

Styling controls
You can customize the appearance of your apps in many ways by using the XAML framework. Styles let you set control properties and reuse those settings for a consistent appearance across multiple controls.

Get the Windows UI Library

Some controls are only available in the Windows UI Library (WinUI), a NuGet package that contains new controls and UI features. To get it, see the Windows UI Library overview and installation instructions.
Starting with WinUI 2.2, the default style for many controls has been updated to use rounded corners. For more info, see Corner radius.

Читайте также:  Safe in cloud для windows portable

Alphabetical index

Detailed information about specific controls and patterns.

  • Animated visual player (see Lottie)
  • Auto-suggest box
  • Button
  • Calendar date picker
  • Calendar view
  • Checkbox
  • Color picker
  • Combo box
  • Command bar
  • Command bar flyout
  • Contact card
  • Content dialog
  • Content link
  • Context menu
  • Date picker
  • Dialogs and flyouts
  • Drop down button
  • Flip view
  • Flyout
  • Forms (pattern)
  • Grid view
  • Hyperlink
  • Hyperlink button
  • Images and image brushes
  • Inking controls
  • List/details (pattern)
  • List view
  • Map control
  • Media playback
  • Menu bar
  • Menu flyout
  • Navigation view
  • Number box
  • Parallax view
  • Password box
  • Person picture
  • Pivot
  • Progress bar
  • Progress ring
  • Radio button
  • Rating control
  • Repeat button
  • Rich edit box
  • Rich text block
  • Scroll viewer
  • Search (pattern)
  • Semantic zoom
  • Shapes
  • Slider
  • Split button
  • Split view
  • Swipe control
  • Tab view
  • Teaching tip
  • Text block
  • Text box
  • Time picker
  • Toggle switch
  • Toggle button
  • Toggle split button
  • Tooltips
  • Tree view
  • Two-pane view
  • Web view

Get the XAML Controls Gallery app from the Microsoft Store to see these controls and the Fluent Design System in action. The app is an interactive companion to this website. When you have it installed, you can use links on individual control pages to launch the app and see the control in action.

Additional controls

Additional controls for Windows development are available from companies such as Telerik, SyncFusion, DevExpress, Infragistics, ComponentOne, and ActiPro. These controls provide additional support for enterprise and .NET developers by augmenting the standard system controls with custom controls and services.

Руководство: Создание пользовательских стилей Tutorial: Create custom styles

В этом учебнике показано, как настроить пользовательский интерфейс приложения XAML. This tutorial shows you how to customize the UI of our XAML app. Внимание! В этом учебнике может присутствовать единорог. А может и не присутствовать. Warning: this tutorial might or might not involve a unicorn. (Он будет!) (It does!)

Пример приложения PhotoLab содержит две страницы. The PhotoLab sample app has two pages. Главная страница, на которой отображается представление фотоальбома, а также сведения о каждом файле изображения. The main page displays a photo gallery view, along with some information about each image file.

Страница сведений, на которой отображается одна выбранная фотография. 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.

Предварительные условия Prerequisites

  • Visual Studio 2019: Скачайте Visual Studio 2019 (выпуск Community Edition бесплатен). Visual Studio 2019: Download Visual Studio 2019 (The Community edition is free.)
  • Пакет SDK для Windows 10 (версии 10.0.17763.0 или выше): скачать последнюю версию Windows SDK (бесплатно) Windows 10 SDK (10.0.17763.0 or later): Download the latest Windows SDK (free)
  • Windows 10, версия 1809 или выше. Windows 10, Version 1809 or later

Часть 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.

Далее необходимо клонировать или скачать пример. Next, you’ll need to clone or download the sample. Нажмите кнопку Clone or download (Клонировать или скачать). Select the Clone or download button. Откроется подменю. A sub-menu appears.

Если вы не знакомы с GitHub: If you’re not familiar with GitHub:

a. a. Нажмите кнопку Download ZIP (Скачать ZIP-файл) и сохраните файл в локальном расположении. Select 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 that you just downloaded, right-click it, and select Extract All. .

c. c. Перейдите к локальной копии примера кода, а затем в каталог Windows-appsample-photo-lab-master\xaml-basics-starting-points\style . Browse to your local copy of the sample, and go to the Windows-appsample-photo-lab-master\xaml-basics-starting-points\style directory.

Если вы знакомы с GitHub: If you are familiar with GitHub:

a. a. Клонируйте главную ветвь репозитория локально. Clone the main branch of the repo locally.

b. b. Перейдите в каталог Windows-appsample-photo-lab\xaml-basics-starting-points\style . Browse to the Windows-appsample-photo-lab\xaml-basics-starting-points\style directory.

Дважды щелкните Photolab.sln , чтобы открыть решение в Visual Studio. Double-click Photolab.sln to open the solution in Visual Studio.

Часть 1. Создание необычного элемента управления ползунка Part 1: Create a fancy slider control

Платформа Windows предоставляет разные способы настройки внешнего вида приложения. Windows app provides a number of ways to customize the look of your app. Доступно множество вариантов — от шрифтов и параметров оформления текста до цветов, градиентов и эффектов размытия. From fonts and typography settings to colors and gradients to blur effects, you have a lot of options.

В первой части учебника мы оформим некоторые элементы управления для редактирования фотографий. For the first part of the tutorial, let’s jazz up some of our photo editing controls.

Эти ползунки выполняют все положенные им функции, но они не совсем обычные. These sliders are nice—they do all the things a slider should do—but they aren’t very fancy. Исправим ситуацию. Let’s fix that.

Ползунок экспозиции регулирует экспозицию изображения: передвиньте его влево, чтобы изображение стало темнее, и вправо, чтобы высветлить изображение. The exposure slider adjusts the exposure of the image: slide it to the left and the image gets darker; slider it to the right and it gets lighter. Сделаем ползунок интереснее, добавив к нему фон с постепенным переходом от черного к белому. Let’s make our slider cooler by giving it a background that goes from black to white. Тогда ползунок будет лучше выглядеть, что уже хорошо, а также появится визуальная подсказка о возможностях этого ползунка. It’ll make the slider look better, which is great, but it will also provide a visual clue about the functionality that the slider provides.

Нажмите клавишу F5, чтобы скомпилировать и запустить приложение. Press F5 to compile and run the app. На первом экране отображается галерея изображений. The first screen shows a gallery of images. Щелкните любое изображение, чтобы перейти на его страницу сведений. Click an image to go to the image details page. Перейдя на страницу сведений, нажмите кнопку редактирования, чтобы просмотреть элементы управления редактированием, с которыми нам предстоит работать. Once you’re there, click the edit button to see the editing controls we’ll be working on. Выйдите из приложения и вернитесь в Visual Studio. Exit the app and return to Visual Studio.

Настройка элемента управления ползунка Customize a slider control

На панели обозревателя решений дважды щелкните файл DetailPage.xaml, чтобы открыть его. In the Solution Explorer panel, double-click DetailPage.xaml to open it.

Используйте элемент Polygon , чтобы создать фоновую фигуру для ползунка экспозиции. Use a Polygon element to create a background shape for the exposure slider.

В пространстве имен Windows.UI.Xaml.Shapes доступно на выбор семь фигур. The Windows.UI.Xaml.Shapes namespace provides seven shapes to choose from. Среди фигур есть эллипс, прямоугольник и элемент «Путь», с помощью которого можно создать любую фигуру — да, даже единорога! There’s an ellipse, a rectangle, and a thing called a Path, which can make any sort of shape—yes, even a unicorn!

Читайте также:  Как установить adobe flash player для windows 10

Узнать больше В статье Рисование фигур содержится вся необходимая информация о фигурах XAML. Read about it: The Draw shapes article tells you everything you need to know about XAML shapes.

Нам нужно создать мини-приложение в форме треугольника, чтобы оно напоминало элемент управления громкостью в стереопроигрывателе. We want to create a triangle-looking widget—something like the shape you’d see on a stereo’s volume control.

В этом нам как раз поможет фигура Polygon ! Sounds like a job for the Polygon shape! Для определения многоугольника необходимо определить набор точек и залить его. To define a polygon, you specify a set of points and give it a fill. Создадим многоугольник шириной примерно 200 пикселей и высотой 20 пикселей с градиентной заливкой. Let’s create a polygon that’s about 200 pixels wide and 20 pixels tall, with a gradient fill.

В файле DetailPage.xaml найдите код ползунка экспозиции и создайте элемент многоугольника прямо перед ним: In DetailPage.xaml, find the code for the exposure slider, then create a Polygon element just before it:

  • Задайте свойству Grid.Row значение «2», чтобы разместить многоугольник в одной строке с ползунком экспозиции. Set Grid.Row to «2» to put the polygon in the same row as the exposure slider.
  • Задайте свойству Points значение «0,20 200,20 200,0», чтобы определить фигуру треугольника. Set the Points property to «0,20 200,20 200,0» to define the triangle shape.
  • Задайте свойству Stretch значение «Fill», а свойству HorizontalAlignment — «Stretch». Set the Stretch property to «Fill» and the HorizontalAlignment property to «Stretch».
  • Задайте свойству Height значение «20», а свойству VerticalAlignment — «Center». Set the Height to «20» and the VerticalAlignment to «Center».
  • Сделайте для Многоугольник линейную градиентную заливку. Give the Polygon a linear gradient fill.
  • На ползунке экспозиции установите для свойства Foreground значение «Transparent» (прозрачный), чтобы многоугольник было видно. On the exposure slider, set the Foreground property to «Transparent» so you can see the polygon.

До Before

После After

  • Обратив внимание на окружающий код XAML, вы увидите, что эти элементы находятся в Grid . If you look at the surrounding XAML, you’ll see that these elements are in a Grid . Мы разместили многоугольник в одной строке с ползунком экспозиции ( Grid.Row=»2″ ), чтобы они отображались в одном месте. We put the polygon in the same row as the exposure slider ( Grid.Row=»2″ ) so they appear in the same spot. Многоугольник расположен перед ползунком, чтобы ползунок отрисовывался поверх фигуры. We put the polygon before the slider so that the slider renders of top of the shape.
  • Мы настроили свойства Stretch=»Fill» и HorizontalAlignment=»Stretch» для многоугольника, чтобы треугольник менял размер для заполнения доступного пространства. We set Stretch=»Fill» and HorizontalAlignment=»Stretch» on the polygon so that the triangle will adjust to fill the available space. Если ширина ползунка уменьшится или увеличится, размеры многоугольника изменятся соответствующим образом. If the slider shrinks or grows in width, the polygon will shrink or grow to match.

Скомпилируйте и запустите приложение. Compile and run the app. Теперь ползунок должен выглядеть замечательно Your slider should now look awesome:

Теперь модернизируем следующий ползунок — ползунок температуры. Let’s give the next slider, the temperature slider, an upgrade. Ползунок температуры изменяет цветовую температуру изображения: если передвинуть его влево, изображение приобретает более синий оттенок, а вправо — желтый. The temperature slider changes the color temperature of the image; sliding to the left makes the image bluer and sliding to the right makes the image more yellow.

Для этой фоновой фигуры мы снова будем использовать многоугольник с теми же размерами, что и у предыдущего, но на сей раз заливкой послужит сине-желтый градиент, а не черно-белый. We’ll use another polygon for this background shape with the same dimensions as the previous one, but this time we’ll make the fill a blue-yellow gradient instead of black and white.

До Before

После After

Скомпилируйте и запустите приложение. Compile and run the app. Теперь у нас два необычных ползунка. You should now have two fancy sliders.

Дополнительные сведения Extra credit

Добавьте фоновую фигуру для ползунка оттенка с градиентом от зеленого к красному. Add a background shape for the tint slider that has a gradient from green to red.

Поздравляем, вы завершили часть 1. Congratulations, you’ve completed part 1! Если вы столкнулись с проблемами или хотите увидеть окончательное решение, готовый код можно найти здесь: https://github.com/Microsoft/Windows-appsample-photo-lab. If you got stuck or want to see the final solution, you can find the completed code at https://github.com/Microsoft/Windows-appsample-photo-lab.

Часть 2. Создание основных стилей Part 2: Create basic styles

Одно из преимуществ стилей XAML заключается в том, что их использование может кардинально сократить объем кода, который требуется написать, а также значительно упростить процесс обновления внешнего вида приложения. One of the advantages of XAML styles is that it can dramatically cut down the amount of code you have to write, and it can make it much, much easier to update the look of your app.

Чтобы определить стиль, необходимо добавить элемент Style в свойство Resources элемента, содержащего элемент управления, который требуется оформить. To define a style, you add a Style element to the Resources property of an element that contains the control you want to style. Если добавить стиль в свойство Page.Resources , стили будут доступны для всей страницы. If you add your style to the Page.Resources property, your styles will be accessible to the entire page. Если добавить стиль в свойство Application.Resources в файле App.xaml, стиль будет доступен всему приложению. If you add your style to the Application.Resources property in your App.xaml file, the style will be accessible to the entire app.

Можно создавать именованные и общие стили. You can create named styles and general styles. Именованный стиль должен быть явным образом применен к конкретным элементам управления, а общий стиль применяется к любому элементу управления, который соответствует указанному атрибуту TargetType . A named style must be explicitly applied to specific controls; a general style is applied to any control that matches the specified TargetType .

В этом примере первый стиль содержит атрибут x:Key и имеет тип целевого объекта Button . In this example, the first style has an x:Key attribute and its target type is Button . Данный ключ задается в свойстве Style , поэтому стиль является именованным и должен применяться явным образом. The first button’s Style property is set to this key, so this style is a named style and must be applied explicitly. Второй стиль применяется ко второй кнопке автоматически, поскольку он имеет тип целевого объекта Button , а в стиле отсутствует атрибут x:Key . The second style is applied automatically to the second button because its target type is Button and the style doesn’t have an x:Key attribute.

Добавим стиль в наше приложение. Let’s add a style to our app. В файле DetailsPage.xaml обратите внимание на текстовые блоки, расположенные рядом с ползунками экспозиции, температуры и оттенка. In DetailsPage.xaml, take a look at the text blocks that sit next to our exposure, temperature, and tint sliders. Каждый из этих текстовых блоков отображает значение ползунка. Each of these text blocks displays the value of a slider. Здесь текстовый блок ползунка экспозиции. Here’s the text block for the exposure slider. Обратите внимание, что свойствам Margin , VerticalAlignment и Padding уже заданы значения. Notice that the Margin , VerticalAlignment , and Padding properties are set.

Читайте также:  Explorer exe ошибка приложения память не может быть read windows

Обратите внимание на другие текстовые блоки — эти свойства имеют в них те же значения. Look at the other text blocks—notice that those same properties are set to the same values. Похоже, это отличный вариант для оформления. Sounds like a good candidate for a style.

Создание стиля текстового блока со значением Create a value text block style

Откройте файл DetailsPage.xaml. Open DetailsPage.xaml.

Найдите элемент управления Grid с именем EditControlsGrid. Find the Grid control named EditControlsGrid. Он содержит наши ползунки и текстовые поля. It contains our sliders and text boxes. Обратите внимание, что сетка уже определяет стиль для ползунков. Notice that the grid already defines a style for our sliders.

Создайте стиль для TextBlock, который задает свойству Margin этого элемента значение «10,8,0,0», свойству VerticalAlignment — «Center», а свойству Padding — «0». Create a style for a TextBlock that sets its Margin to «10,8,0,0», its VerticalAlignment to «Center», and its Padding to «0».

До Before

После After

Создадим именованный стиль, чтобы указать, к каким элементам управления TextBlock он применяется. Let’s make this a named style so we can specify which TextBlock controls it applies to. Установите для свойства x:Key этого стиля значение ValueTextBlock. Set the style’s x:Key property to «ValueTextBlock».

До Before

После After

Удалите свойства Margin , VerticalAlignment и Padding каждого элемента TextBlock , а свойству Style задайте значение . For each TextBlock , remove its Margin , VerticalAlignment , and Padding properties, and set its Style property to ««.

До Before

После After

Сделайте это для всех шести элементов управления TextBlock, связанных с ползунками. Make this change to all 6 TextBlock controls associated with the sliders.

Скомпилируйте и запустите приложение. Compile and run the app. Теперь оно выглядит. так же. It should look. the same. Но вы должны чувствовать то прекрасное чувство удовлетворения и завершенности, которое приходит от написания эффективного и поддерживаемого кода. But you should feel that wonderful sense of satisfaction and accomplishment that comes from writing efficient, maintainable code.

Поздравляем, вы завершили часть 2. Congratulations, you’ve completed Part 2!

Часть 3. Использование шаблона элемента управления для создания необычного ползунка Part 3: Use a control template to make a fancy slider

Помните, как в части 1 мы добавили фигуру под ползунок, чтобы он выглядел лучше? Remember, how in Part 1 we added a shape behind the slider to make it look cool?

Мы справились с задачей, но есть более эффективный способ получить тот же результат — можно создать шаблон элемента управления. Well, we got the job done, but there’s a better way to achieve the same effect: create a control template.

На панели обозревателя решений дважды щелкните файл DetailPage.xaml. In the Solution Explorer panel, double-click DetailPage.xaml.

Далее мы воспользуемся шаблоном элемента управления для ползунка в качестве отправной точки. Next, we’ll use the default control template for slider as our starting point. Добавьте этот код XAML в элемент Page.Resources . Add this XAML to the Page.Resources element. (Элемент Page.Resources находится ближе к началу страницы.) (The Page.Resources element is toward the beginning of the page.)

Это приложение использует библиотеку пользовательского интерфейса Windows (WinUI), поэтому вы можете скопировать шаблон по умолчанию из репозитория WinUI в GitHub: Slider_themeresources.xaml. This app uses the Windows UI Library (WinUI), so you can copy the default template from the WinUI GitHub repo: Slider_themeresources.xaml.

Этот код XAML занимает немало места! Wow, that’s a lot of XAML! Шаблоны элементов управления — полезная функция, но они могут быть довольно сложными, поэтому обычно следует начинать с шаблона по умолчанию. Control templates are a powerful feature, but they can be quite complex, which is why it’s usually a good idea to start from the default template.

В только что добавленном шаблоне ControlTemplate найдите элемент управления сетки с именем HorizontalTemplate . Within the ControlTemplate you just added, find the grid control named HorizontalTemplate . Эта сетка определяет ту часть шаблона, которую мы будем изменять. This grid defines the portion of the template that we want to change.

Создайте такой же многоугольник, что и для ползунка экспозиции в части 1. Create a polygon that’s just like the polygon you created for the exposure slider in Part 1. Добавьте этот многоугольник после закрывающего тега Grid.RowDefinitions . Add the polygon after the closing Grid.RowDefinitions tag. Установите для Grid.Row значение «0», для Grid.RowSpan — «3», а для Grid.ColumnSpan — «3». Set Grid.Row to «0», Grid.RowSpan to «3», and Grid.ColumnSpan to «3».

До Before

После After

Удалите параметр Polygon.Fill . Remove the Polygon.Fill setting. Задайте для параметра Fill значение «» . Set Fill to «» . Это необходимо, чтобы при установке значения для свойства Background ползунка также устанавливалось значение для свойства Fill многоугольника. This makes it so that setting the Background property of the slider sets the Fill property of the polygon.

До Before

После After

Сразу после добавленного многоугольника находится прямоугольник с именем HorizontalTrackRect . Just after the polygon you added, there’s a rectangle named HorizontalTrackRect . Удалите параметр Fill этого прямоугольника, чтобы он стал невидимым и не загораживал фигуру многоугольника. Remove the Rectangle’s Fill setting so that the rectangle won’t be visible and won’t block our polygon shape. (Полностью удалять прямоугольник не нужно, так как шаблон элемента управления использует его для визуальных эффектов взаимодействия, таких как наведение.) (We don’t want to completely remove the rectangle because the control template also uses it for interaction visuals, such as hover.)

До Before

После After

Шаблон готов. You’re done with the template! Теперь применим его к ползункам. Now we need to apply it to our sliders.

Обновим ползунок экспозиции. Let’s update our exposure slider.

  • Задайте для свойства Template ползунка значение «» . Set the slider’s Template property to «» .
  • Удалите параметр Background=»Transparent» ползунка. Remove the slider’s Background=»Transparent» setting.
  • Задайте для Background ползунка линейный градиент с переходом от черного к белому. Set the slider’s Background to a linear gradient that transitions from black to white.
  • Удалите фоновый многоугольник, созданный в части 1. Remove the background polygon we created in Part 1.

До Before

После After

Внесите те же изменения для ползунка температуры. Make the same updates to the temperature slider.

До Before

После After

Внесите те же изменения для ползунка оттенка. Make the same updates to the tint slider.

До Before

После After

Скомпилируйте и запустите приложение. Compile and run the app.

Как видно, внесенные изменения улучшили расположение многоугольника: теперь его нижняя часть выровнена относительно нижней части бегунка ползунка. As you can see, our updates improved the positioning of the polygon; now the bottom of the polygon is aligned to the bottom of the slider thumb.

Оцените статью