• Главная
  • Карта сайта
Не найдено

Кнопки - Windows UWP applications

  1. Вибір правильного елемента управління Is this the right control?
  2. приклади Examples
  3. Створення кнопки Create a button
  4. Взаємодія з кнопкою Button interaction
  5. Вміст кнопки Button content
  6. Створення кнопки повтору Create a repeat button
  7. Створення розкривається кнопки Create a drop down button
  8. Приклад. Розкривається кнопка Example - Drop down button
  9. Створення розгортається кнопки Create a split button
  10. Приклад. Розгортається кнопка Example - Split button
  11. Створення розгортається кнопки з перемикачем Create a toggle split button
  12. Відмінності від кнопки перемикання Differences with ToggleButton
  13. Приклад. Розгортається кнопка з перемикачем Example - Toggle split button
  14. рекомендації Recommendations
  15. Рекомендується макет з однією кнопкою Recommended single button layout
  16. Кнопки "Назад" Back buttons

Кнопка надає користувачеві можливість викликати негайне дію. A button gives the user a way to trigger an immediate action. Деякі кнопки призначені спеціально для конкретних завдань, таких як навігація, повторювані дії або вiдтворення меню. Some buttons are specialized for particular tasks, such as navigation, repeated actions, or presenting menus.

Платформа XAML надає стандартний елемент керування "кнопка", а також кілька спеціальних таких елементів. The XAML framework provides a standard button control as well as several specialized button controls.

Елемент управління Control Опис Description Button Button Ініціює негайне дію. Initiates an immediate action. Може використовуватися з подією Click кнопки або прив'язкою команд. Can be used with a Click event or Command binding. RepeatButton RepeatButton Кнопка, яка в натиснутому стані постійно викликає подія Click. A button that raises a Click event continuously while pressed. HyperlinkButton HyperlinkButton Стилізована під гіперпосилання кнопка, яка використовується для навігації. A button that's styled like a hyperlink, used for navigation. Детальніше див. На сторінці гіперпосилання . See Hyperlinks for more info. DropDownButton DropDownButton Кнопка зі значком шеврони, яка відкриває прикріплене спливаюче меню. A button with a chevron to open an attached flyout. SplitButton SplitButton Двостороння кнопка. A button with two sides. Одна сторона ініціює дію, а інша відкриває меню. One side initiates an action, and the other side opens a menu. ToggleSplitButton ToggleSplitButton Двостороння кнопка перемикання. A toggle button with two sides. Одна сторона виконує функцію перемикача, а інша сторона відкриває меню. One side toggles on / off, and the other side opens a menu. Отримання бібліотеки призначеного для користувача інтерфейсу Windows Get the Windows UI Library DropDownButton, SplitButton і ToggleSplitButton є компонентами бібліотеки призначеного для користувача інтерфейсу Windows - пакета NuGet, в який входять нові елементи управління, а також компоненти для користувача інтерфейсу для додатків UWP. DropDownButton, SplitButton, and ToggleSplitButton are included as part of the Windows UI Library, a NuGet package that contains new controls and UI features for UWP apps. Додаткові відомості, включаючи інструкції з установки, див. В оглядовій статті про бібліотеку призначеного для користувача інтерфейсу Windows . For more info, including installation instructions, see the Windows UI Library overview .

Вибір правильного елемента управління Is this the right control?

Кнопка дозволяє користувачеві ініціювати негайне дію, наприклад відправити форму. Use a Button to let the user initiate an immediate action , such as submitting a form.

Не використовуйте кнопку для переходу на іншу сторінку. Замість неї використовуйте кнопку HyperlinkButton . Do not use a button when the action is to navigate to another page; use a HyperlinkButton instead. Детальніше див. На сторінці гіперпосилання . See Hyperlinks for more info.

Виняток: Для навігації по майстру використовуйте кнопки "Назад" і "Вперед". Exception: For wizard navigation, use buttons labeled "Back" and "Next". Для інших видів навігації на рівень вище або нижче використовуйте кнопку "Назад" . For other types of backwards navigation or navigation to an upper level, use a back button .

Кнопка RepeatButton дозволяє користувачеві повторно викликати дію. Use a RepeatButton when the user might want to trigger an action repeatedly . Наприклад, за допомогою цієї кнопки можна збільшити або зменшувати значення в лічильнику. For example, use a RepeatButton to increment or decrement a value in a counter.

Кнопку DropDownButton слід використовувати при наявності спливаючого меню, що містить додаткові варіанти. Use a DropDownButton when the button has a flyout that contains more options . Значок шеврони за замовчуванням є візуальним індикатором наявності у кнопки спливаючого меню. The default chevron provides a visual indication that the button includes a flyout.

Кнопка SplitButton дозволяє користувачеві ініціювати негайне дію або окремо вибирати додаткові варіанти. Use a SplitButton when you want the user to be able to initiate an immediate action or choose from additional options independently .

приклади Examples

У цьому прикладі використовуються дві кнопки, "Дозволити" і "Блокувати", в діалоговому вікні, яке запитує доступ до розташування. This example uses two buttons, Allow and Block, in a dialog requesting location access.

Створення кнопки Create a button

У цьому прикладі розглядається реакція кнопки на клацання. This example shows a button that responds to a click.

Створіть кнопку в XAML. Create the button in XAML.

<Button Content = "Subscribe" Click = "SubscribeButton_Click" />

Або створіть кнопку в коді. Or create the button in code.

Button subscribeButton = new Button (); subscribeButton.Content = "Subscribe"; subscribeButton.Click + = SubscribeButton_Click; // Add the button to a parent container in the visual tree. stackPanel1.Children.Add (subscribeButton);

Обробіть подія "Click". Handle the Click event.

private async void SubscribeButton_Click (object sender, RoutedEventArgs e) {// Call app specific code to subscribe to the service. For example: ContentDialog subscribeDialog = new ContentDialog {Title = "Subscribe to App Service?", Content = "Listen, watch, and play in high definition for only $ 9.99 / month. Free to try, cancel anytime.", CloseButtonText = "Not Now ", PrimaryButtonText =" Subscribe ", SecondaryButtonText =" Try it "}; ContentDialogResult result = await subscribeDialog.ShowAsync (); }

Взаємодія з кнопкою Button interaction

Якщо торкнутися кнопки пальцем або стилусом або навести на неї вказівник і натиснути ліву кнопку миші, кнопка викликає подія Click . When you tap a Button with a finger or stylus, or press a left mouse button while the pointer is over it, the button raises the Click event. Якщо для кнопки передбачений фокус клавіатури, при натиснути клавішу ENTER або ПРОБІЛ також відбувається виклик події "Click". If a button has keyboard focus, pressing the Enter key or the Spacebar key also raises the Click event.

Як правило, не можна обробляти низькорівневі події PointerPressed за допомогою елемента Button, так як для нього передбачено поведінку Click. You generally can not handle low-level PointerPressed events on a Button because it has the Click behavior instead. Додаткові відомості див. У розділі Загальні відомості про події та перенаправлених події . For more info, see Events and routed events overview .

Можна вибирати порядок виклику події Click шляхом зміни властивості ClickMode . You can change how a button raises the Click event by changing the ClickMode property. Значним ClickMode за замовчуванням є Release, однак для режиму ClickMode кнопки можна задати значення Hover або Press. The default ClickMode value is Release, but you also can set a button's ClickMode to Hover or Press . Якщо для параметра ClickMode вибрано значення Hover, подія "Click" неможливо викликати натисканням клавіші або киснем. If ClickMode is Hover, the Click event can not be raised with the keyboard or touch .

Вміст кнопки Button content

Кнопка є елементом ContentControl . Button is a ContentControl . Її властивість вмісту XAML - Content , Завдяки чому можливе використання подібного синтаксису: <Button> A button's content </ Button>. Its XAML content property is Content , Which enables a syntax like this for XAML: <Button> A button's content </ Button>. Як вміст кнопки можна задати будь-який об'єкт. You can set any object as the button's content. Якщо вмістом є клас UIElement , Він обробляється для перегляду в кнопці. If the content is a UIElement , It is rendered in the button. Якщо вмістом є інший тип об'єкта, в кнопці відображається його строкове представлення. If the content is another type of object, its string representation is shown in the button.

Вміст кнопки зазвичай являє собою текст. A button's content is usually text. Нижче наведені рекомендації по дизайну кнопок з текстовим вмістом: Here are design recommendations for buttons with text content:

  • Використовуйте короткий, конкретний, який не потребує роз'яснень текст, який чітко описує дію, яке виконує кнопкою. Use a concise, specific, self-explanatory text that clearly describes the action that the button performs. Зазвичай текст напису на кнопці складається з одного слова - як правило, дієслова. Usually button text content is a single word, a verb.
  • Використовуйте шрифт, заданий за замовчуванням, якщо відповідно до стилю торгової марки не потрібно використовувати інший. Use the default font unless your brand guidelines tell you to use something different.
  • При розміщенні короткого тексту уникайте використання вузьких кнопок. Мінімальна ширина кнопки повинна складати 120 пікселів. For shorter text, avoid narrow command buttons by using a minimum button width of 120px.
  • При розміщенні довгого тексту уникайте використання широких кнопок. Довжина тексту повинна складати не більше 26 символів. For longer text, avoid wide command buttons by limiting text to a maximum length of 26 characters.
  • Якщо текст напису на кнопці динамічний (тобто він локалізуемое ), Продумайте, яким чином можна змінювати розмір кнопки і як це вплине на елементи управління, які її оточують. If the button's text content is dynamic (ie, it is localized ), Consider how the button will resize and what will happen to controls around it.

Можна також налаштувати візуальні елементи, складові зовнішній вигляд кнопки. You can also customize visuals that make up the button's appearance. Наприклад, можна замінити текст значком або використовувати значок і текст. For example, you could replace the text with an icon, or use an icon plus text.

В даному випадку клас StackPanel, що містить зображення і текст, заданий в якості вмісту кнопки. Here, a StackPanel that contains an image and text is set as the content of a button .

<Button Click = "Button_Click" Background = "LightGray" Height = "100" Width = "80"> <StackPanel> <Image Source = "Assets / Photo.png" Height = "62" /> <TextBlock Text = "Photos "Foreground =" Black "HorizontalAlignment =" Center "/> </ StackPanel> </ Button>

Кнопка виглядає наступним чином. The button looks like this.

Створення кнопки повтору Create a repeat button

RepeatButton - це кнопка, при натисканні якої події Click повторюються до тих пір, поки вона не буде відпущена. A RepeatButton is a button that raises Click events repeatedly from the time it's pressed until it's released. Задайте властивість Delay , Щоб вказати час затримки після натискання кнопки, після якого почнеться повторення дії клацання. Set the Delay property to specify the time that the RepeatButton waits after it is pressed before it starts repeating the click action. Задайте властивість Interval , Щоб вказати час між повтореннями дії клацання. Set the Interval property to specify the time between repetitions of the click action. Час для обох властивостей вказується в мілісекундах. Times for both properties are specified in milliseconds.

У наступному прикладі показані два елементи управління RepeatButton, чиї відповідні події "Click" використовуються для збільшення і зменшення значення, наведеного в блоці тексту. The following example shows two RepeatButton controls whose respective Click events are used to increase and decrease the value shown in a text block.

<StackPanel> <RepeatButton Width = "100" Delay = "500" Interval = "100" Click = "Increase_Click"> Increase </ RepeatButton> <RepeatButton Width = "100" Delay = "500" Interval = "100" Click = "Decrease_Click"> Decrease </ RepeatButton> <TextBlock x: Name = "clickTextBlock" Text = "Number of Clicks:" /> </ StackPanel> private static int _clicks = 0; private void Increase_Click (object sender, RoutedEventArgs e) {_clicks + = 1; clickTextBlock.Text = "Number of Clicks:" + _clicks; } Private void Decrease_Click (object sender, RoutedEventArgs e) {if (_clicks> 0) {_clicks - = 1; clickTextBlock.Text = "Number of Clicks:" + _clicks; }}

Створення розкривається кнопки Create a drop down button

Для створення розкривається кнопки (DropDownButton) потрібно Windows 10, версія 1809 ( пакет SDK 17763 ) Або пізніша, або бібліотека для користувача інтерфейсу Windows . DropDownButton requires Windows 10, version 1809 ( SDK 17763 ) Or later, or the Windows UI Library .

DropDownButton - це кнопка, яка використовує шеврон в якості візуального індикатора прикріпленого спливаючого меню, яке містить додаткові варіанти. A DropDownButton is a button that shows a chevron as a visual indicator that it has an attached flyout that contains more options. Вона діє як і стандартна кнопка зі спливаючих меню, однак її зовнішній вигляд відрізняється. It has the same behavior as a standard Button with a flyout; only the appearance is different.

Розкривається кнопка успадковує подія Click, але зазвичай воно не використовується. The drop down button inherits the Click event, but you typically do not use it. Замість цього ви використовуєте властивість для приєднання спливаючого меню і виклику дії за допомогою команд в цьому меню. Instead, you use the Flyout property to attach a flyout and invoke actions using menu options in the flyout. Спливаюче меню відкривається автоматично при натисканні кнопки. The flyout opens automatically when the button is clicked. Не забудьте поставити для спливаючого меню властивість Placement , Щоб розмістити меню по відношенню до кнопки за потрібне чином. Be sure to specify the Placement property of your flyout to ensure the desired placement in relation to the button. Алгоритм розміщення за замовчуванням може не забезпечити передбачуване розміщення у всіх ситуаціях. The default placement algorithm might not produce the intended placement in all situations.

Приклад. Розкривається кнопка Example - Drop down button

У наведеному тут прикладі показано, як створити розкривається кнопку зі спливаючих меню, що містить команди для вирівнювання абзацу в елементі RichEditBox. This example shows how to create a drop down button with a flyout that contains commands for paragraph alignment in a RichEditBox. (За докладнішою інформацією та код см. В статті Блок форматируемого тексту .) (For more info and code, see Rich edit box ).

<DropDownButton ToolTipService.ToolTip = "Alignment"> <TextBlock FontFamily = "Segoe MDL2 Assets" FontSize = "14" Text = "& # xE8E4;" /> <DropDownButton.Flyout> <MenuFlyout Placement = "BottomEdgeAlignedLeft"> <MenuFlyoutItem Text = "Left" Icon = "AlignLeft" Tag = "left" Click = "AlignmentMenuFlyoutItem_Click" /> <MenuFlyoutItem Text = "Center" Icon = "AlignCenter" Tag = "center" Click = "AlignmentMenuFlyoutItem_Click" /> <MenuFlyoutItem Text = " Right "Icon =" AlignRight "Tag =" right "Click =" AlignmentMenuFlyoutItem_Click "/> </ MenuFlyout> </DropDownButton.Flyout> </ DropDownButton> private void AlignmentMenuFlyoutItem_Click (object sender, RoutedEventArgs e) {var option = ((MenuFlyoutItem ) sender) .Tag.ToString (); Windows.UI.Text.ITextSelection selectedText = editor.Document.Selection; if (selectedText! = null) {// Apply the alignment to the selected paragraphs. var paragraphFormatting = selectedText.ParagraphFormat; if (option == "left") {paragraphFormatting.Alignment = Windows.UI.Text.ParagraphAlignment.Left; } Else if (option == "center") {paragraphFormatting.Alignment = Windows.UI.Text.ParagraphAlignment.Center; } Else if (option == "right") {paragraphFormatting.Alignment = Windows.UI.Text.ParagraphAlignment.Right; }}}

Створення розгортається кнопки Create a split button

Для створення дедалі ширшої кнопки потрібно Windows 10, версія 1809 ( пакет SDK 17763 ) Або пізніша, або бібліотека для користувача інтерфейсу Windows . SplitButton requires Windows 10, version 1809 ( SDK 17763 ) Or later, or the Windows UI Library .

кнопка SplitButton складається з двох частин, які можна викликати окремо. A SplitButton has two parts that can be invoked separately. Одна частина являє собою стандартну кнопку, яка викликає негайне дію. One part behaves like a standard button and invokes an immediate action. Інша частина дозволяє викликати спливає елемент з додатковими параметрами, які користувач може вибрати. The other part invokes a flyout that contains additional options that the user can choose from.

Примітка

При виклику дії за допомогою дотику розгортається кнопка виконує функцію розкривається кнопки. Обидві сторони кнопки викликають контекстне меню. When invoked with touch, the split button behaves as a drop down button; both halves of the button invoke the flyout. При використанні інших методів введення користувач може викликати кожен елемент кнопки окремо. With other methods of input, a user can invoke either half of the button separately.

Стандартну поведінку розгортається кнопки: The typical behavior for a split button is:

  • При натисканні однієї зі сторін кнопки має оброблятися подія Click для ініціювання варіанту, обраного в спадному меню. When the user clicks the button part, handle the Click event to invoke the option that's currently selected in the drop down.
  • При відкритті списку повинен оброблятися виклик елементів в ньому для зміни обраного варіанту, а потім його виклику. When the drop down is open, handle invocation of the items in the drop down to both change which option is selected, and then invoke it. Виклик елемента у спливаючому меню грає важливу роль, так як подія Click НЕ буде запускатися при торканні. It's important to invoke the flyout item because the button Click event does not occur when using touch.

Порада

Існує багато способів розташування елементів в списку і обробки їх виклику. There are many ways to put items in the drop down and handle their invocation. Якщо ви використовуєте ListView або GridView, можна обробити подія SelectionChanged. If you use a ListView or GridView, one way is to handle the SelectionChanged event. Після цього задайте для параметра SingleSelectionFollowsFocus значення false. If you do this, set SingleSelectionFollowsFocus to false. Ця установка дозволить користувачам переходити за варіантами за допомогою клавіатури без виклику варіанту при кожному внесенні змін. This lets users navigate the options using a keyboard without invoking the item on each change.

Приклад. Розгортається кнопка Example - Split button

У наведеному тут прикладі показано, як створити розгортається кнопку для зміни кольору переднього плану обраного тексту в елементі RichEditBox. This example shows how to create a split button that is used to change the foreground color of selected text in a RichEditBox. (За докладнішою інформацією та код см. В статті Блок форматируемого тексту .) (For more info and code, see Rich edit box ). Спливаюче меню розгортається кнопки за замовчуванням використовує для властивості Placement значення BottomEdgeAlignedLeft . Split button's flyout uses BottomEdgeAlignedLeft as the default value for its Placement property. Ви не можете перевизначити це значення. You can not override this value.

<SplitButton ToolTipService.ToolTip = "Foreground color" Click = "BrushButtonClick"> <Border x: Name = "SelectedColorBorder" Width = "20" Height = "20" /> <SplitButton.Flyout> <Flyout x: Name = "BrushFlyout "> <! - Set SingleSelectionFollowsFocus =" False "so that keyboard navigation works correctly. -> <GridView ItemsSource = "{x: Bind ColorOptions}" SelectionChanged = "BrushSelectionChanged" SingleSelectionFollowsFocus = "False" SelectedIndex = "0" Padding = "0"> <GridView.ItemTemplate> <DataTemplate> <Rectangle Fill = "{ Binding} "Width =" 20 "Height =" 20 "/> </ DataTemplate> </GridView.ItemTemplate> <GridView.ItemContainerStyle> <Style TargetType =" GridViewItem "> <Setter Property =" Margin "Value =" 2 " /> <Setter Property = "MinWidth" Value = "0" /> <Setter Property = "MinHeight" Value = "0" /> </ Style> </GridView.ItemContainerStyle> </ GridView> </ Flyout> </ SplitButton.Flyout> </ SplitButton> public sealed partial class MainPage: Page {// Color options that are bound to the grid in the split button flyout. private List <SolidColorBrush> ColorOptions = new List <SolidColorBrush> (); private SolidColorBrush CurrentColorBrush = null; public MainPage () {this.InitializeComponent (); // Add color brushes to the collection. ColorOptions.Add (new SolidColorBrush (Colors.Black)); ColorOptions.Add (new SolidColorBrush (Colors.Red)); ColorOptions.Add (new SolidColorBrush (Colors.Orange)); ColorOptions.Add (new SolidColorBrush (Colors.Yellow)); ColorOptions.Add (new SolidColorBrush (Colors.Green)); ColorOptions.Add (new SolidColorBrush (Colors.Blue)); ColorOptions.Add (new SolidColorBrush (Colors.Indigo)); ColorOptions.Add (new SolidColorBrush (Colors.Violet)); ColorOptions.Add (new SolidColorBrush (Colors.White)); } Private void BrushButtonClick (object sender, object e) {// When the button part of the split button is clicked, // apply the selected color. ChangeColor (); } Private void BrushSelectionChanged (object sender, SelectionChangedEventArgs e) {// When the flyout part of the split button is opened and the user selects // an option, set their choice as the current color, apply it, then close the flyout. CurrentColorBrush = (SolidColorBrush) e.AddedItems [0]; SelectedColorBorder.Background = CurrentColorBrush; ChangeColor (); BrushFlyout.Hide (); } Private void ChangeColor () {// Apply the color to the selected text in a RichEditBox. Windows.UI.Text.ITextSelection selectedText = editor.Document.Selection; if (selectedText! = null) {Windows.UI.Text.ITextCharacterFormat charFormatting = selectedText.CharacterFormat; charFormatting.ForegroundColor = CurrentColorBrush.Color; selectedText.CharacterFormat = charFormatting; }}}

Створення розгортається кнопки з перемикачем Create a toggle split button

Для створення ToggleSplitButton потрібно Windows 10, версія 1809 ( пакет SDK 17763 ) Або пізніша, або бібліотека для користувача інтерфейсу Windows . ToggleSplitButton requires Windows 10, version 1809 ( SDK 17763 ) Or later, or the Windows UI Library .

кнопка ToggleSplitButton складається з двох частин, які можна викликати окремо. A ToggleSplitButton has two parts that can be invoked separately. Одна частина виконує функцію перемикача. One part behaves like a toggle button that can be on or off. Інша частина дозволяє викликати спливає елемент з додатковими параметрами, які користувач може вибрати. The other part invokes a flyout that contains additional options that the user can choose from.

Розгортається кнопка з перемикачем зазвичай використовується для активації або деактивації компонента, якщо компонент містить безліч можливостей, з яких користувач може вибирати. A toggle split button is typically used to enable or disable a feature when the feature has multiple options that the user can choose from. Наприклад, в редакторі документів вона може використовуватися для включення або виключення списків, а список, що розкривається - для вибору стилю списку. For example, in a document editor, it could be used to turn lists on or off, while the drop down is used to choose the style of the list.

Примітка

При виклику с помощью Дотик розгортається кнопка з Перемикач працює аналогічно розкрівається кнопці. When invoked with touch, the toggle split button behaves as a drop down button. При використанні інших способів введення користувач може перемикати і викликати два елементи кнопки окремо. With other methods of input, a user can toggle and invoke the two halves of the button separately. При торканні обидва елементи кнопки викликають контекстне меню. With touch, both halves of the button invoke the flyout. Отже, необхідно додати в вміст спливаючого меню варіант для включення і виключення кнопки. Therefore, you must include an option in your flyout content to toggle the button on or off.

Відмінності від кнопки перемикання Differences with ToggleButton

На Відміну Від кнопки перемикання (ToggleButton), у розгортається кнопки з перемикачем (ToggleSplitButton) немає невизначеного стану. Unlike ToggleButton , ToggleSplitButton does not have an indeterminate state. З цієї причини ви повинні враховувати наступні відмінності: As a result, you should keep in mind these differences:

  • Кнопка ToggleSplitButton не має властивість IsThreeState або подією Indeterminate. ToggleSplitButton does not have an IsThreeState property or Indeterminate event .
  • властивість ToggleSplitButton.IsChecked приймає логічне значення і не допускає логічне значення NULL. The ToggleSplitButton.IsChecked property is just a bool, not a nullable bool.
  • ToggleSplitButton працює тільки з подією IsCheckedChanged . Вона не підтримує окремі події Checked і Unchecked. ToggleSplitButton has only the IsCheckedChanged event; it does not have separate Checked and Unchecked events .

Приклад. Розгортається кнопка з перемикачем Example - Toggle split button

У наведеному тут прикладі показано, як розгортається кнопка з перемикачем може використовуватися для включення або виключення форматування списку, а також зміни стилю списку в елементі RichEditBox. The following example shows how a toggle split button could be used to turn list formatting on or off, and change the style of the list, in a RichEditBox. (За докладнішою інформацією та код см. В статті Блок форматируемого тексту .) (For more info and code, see Rich edit box ). Спливаюче меню розгортається кнопки з перемикачем за замовчуванням використовує для властивості Placement значення BottomEdgeAlignedLeft . Toggle split button's flyout uses BottomEdgeAlignedLeft as the default value for its Placement property. Ви не можете перевизначити це значення. You can not override this value.

<ToggleSplitButton x: Name = "ListButton" ToolTipService.ToolTip = "List style" Click = "ListButton_Click" IsCheckedChanged = "ListStyleButton_IsCheckedChanged"> <TextBlock FontFamily = "Segoe MDL2 Assets" FontSize = "14" Text = "& # xE8FD;" /> <ToggleSplitButton.Flyout> <Flyout> <ListView x: Name = "ListStylesListView" SelectionChanged = "ListStylesListView_SelectionChanged" SingleSelectionFollowsFocus = "False"> <StackPanel Tag = "bullet" Orientation = "Horizontal"> <FontIcon FontFamily = "Segoe MDL2 Assets "Glyph =" & # xE7C8; "/> <TextBlock Text =" Bullet "Margin =" 8,0 "/> </ StackPanel> <StackPanel Tag =" alpha "Orientation =" Horizontal "> <TextBlock Text =" A "FontSize =" 24 "Margin =" 2,0 "/> <TextBlock Text =" Alpha "Margin =" 8 "/> </ StackPanel> <StackPanel Tag =" numeric "Orientation =" Horizontal "> <FontIcon FontFamily = "Segoe MDL2 Assets" Glyph = "& # xF146;" /> <TextBlock Text = "Numeric" Margin = "8,0" /> </ StackPanel> <TextBlock Tag = "none" Text = "None" Margin = "28,0" /> </ ListView> </ Flyout> </ToggleSplitButton.Flyout> </ ToggleSplitButton> priv ate void ListStyleButton_IsCheckedChanged (ToggleSplitButton sender, ToggleSplitButtonIsCheckedChangedEventArgs args) {// Use the toggle button to turn the selected list style on or off. if (((ToggleSplitButton) sender) .IsChecked == true) {// On. Apply the list style selected in the drop down to the selected text. var listStyle = ((FrameworkElement) (ListStylesListView.SelectedItem)). Tag.ToString (); ApplyListStyle (listStyle); } Else {// Off. Make the selected text not a list, // but do not change the list style selected in the drop down. ApplyListStyle ( "none"); }} Private void ListStylesListView_SelectionChanged (object sender, SelectionChangedEventArgs e) {var listStyle = ((FrameworkElement) (e.AddedItems [0])). Tag.ToString (); if (ListButton.IsChecked == true) {// Toggle button is on. Turn it off ... if (listStyle == "none") {ListButton.IsChecked = false; } Else {// or apply the new selection. ApplyListStyle (listStyle); }} Else {// Toggle button is off. Turn it on, which will apply the selection // in the IsCheckedChanged event handler. ListButton.IsChecked = true; }} Private void ApplyListStyle (string listStyle) {Windows.UI.Text.ITextSelection selectedText = editor.Document.Selection; if (selectedText! = null) {// Apply the list style to the selected text. var paragraphFormatting = selectedText.ParagraphFormat; if (listStyle == "none") {paragraphFormatting.ListType = Windows.UI.Text.MarkerType.None; } Else if (listStyle == "bullet") {paragraphFormatting.ListType = Windows.UI.Text.MarkerType.Bullet; } Else if (listStyle == "numeric") {paragraphFormatting.ListType = Windows.UI.Text.MarkerType.Arabic; } Else if (listStyle == "alpha") {paragraphFormatting.ListType = Windows.UI.Text.MarkerType.UppercaseEnglishLetter; } SelectedText.ParagraphFormat = paragraphFormatting; }}

рекомендації Recommendations

  • Зробіть так, щоб призначення і стан кнопки було зрозуміло користувачеві. Make sure the purpose and state of a button are clear to the user.
  • Якщо для одного рішення передбачено кілька кнопок (наприклад, в діалоговому вікні підтвердження), розташуйте ці кнопки в такому порядку, де [Виконати] і [Do Not виконувати] будуть конкретними варіантами відповіді на основну команду: When there are multiple buttons for the same decision ( such as in a confirmation dialog), present the commit buttons in this order, where [Do it] and [Do not do it] are specific responses to the main instruction:
    • ОК / [Виконати] / Так OK / [Do it] / Yes
    • [Чи не виконувати] / Нет [Do not do it] / No
    • скасування Cancel
  • Зробіть одночасно доступними користувачеві тільки одну або дві кнопки, наприклад "Прийняти" і "Відхилити". Expose only one or two buttons to the user at a time, for example, Accept and Cancel. Якщо потрібно надати користувачеві більше дій, введіть в інтерфейс прапорці або перемикачі , За допомогою яких користувач зможе вибрати потрібні дії, а потім шляхом натискання однієї кнопки почати виконання всіх цих дій. If you need to expose more actions to the user, consider using checkboxes or radio buttons from which the user can select actions, with a single command button to trigger those actions.
  • Для дії, яке потрібно виконати над багатьма сторінками вашого застосування, краще використовувати нижню панель додатки , А не повторювати відповідну кнопку на кожній сторінці. For an action that needs to be available across multiple pages within your app, instead of duplicating a button on multiple pages, consider using a bottom app bar .

Рекомендується макет з однією кнопкою Recommended single button layout

Якщо в макеті потрібно тільки одна кнопка, вона повинна бути вирівняна або по лівому, або по правому краю на основі контексту її контейнера. If your layout requires only one button, it should be either left- or right-aligned based on its container context.

  • У діалогових вікнах з однією кнопкою потрібно вирівнювання кнопки по правому краю. Dialogs with only one button should right-align the button. Якщо діалогове вікно містить тільки одну кнопку, переконайтеся, що вона виконує безпечне, оборотне дію. If your dialog contains only one button, ensure that the button performs the safe, nondestructive action. Если ви вікорістовуєте ContentDialog і вкажете одну кнопку, вона буде автоматично вирівняна по правому краю. If you use ContentDialog and specify a single button, it will automatically right-align.

  • Якщо кнопка відображається всередині контейнера призначеного для користувача інтерфейсу (наприклад, у спливаючому повідомленні, спливаючому елементі меню або елементі подання списку), необхідно вирівняти кнопку в контейнері по правому краю. If your button appears within a container UI (for example, within a toast notification, a flyout, or a list view item), you should right-align the button within the container.

  • На сторінках, що містять одну кнопку (наприклад, кнопку "Застосувати" в нижній частині сторінки параметрів), необхідно вирівняти кнопку по лівому краю. In pages that contain a single button (for example, an "Apply" button at the bottom of a settings page), you should left-align the button. Це забезпечить відповідність кнопки решти вмісту сторінки. This ensures that the button aligns with the rest of the page content.

Кнопки "Назад" Back buttons

Кнопка "Назад" - це наданий системою елемент призначеного для користувача інтерфейсу для зворотного навігації через зворотний стек або журнал навігації користувача. The back button is a system-provided UI element that enables backward navigation through either the back stack or navigation history of the user. Ви не зобов'язані створювати власну кнопку "Назад", але ви можете виконати певні дії, щоб реалізувати хороші можливості зворотного навігації. You do not have to create your own back button, but you might have to do some work to enable a good backwards navigation experience. Додаткові відомості див. У розділі Журнал і навігація в зворотному напрямку For more info, see History and backwards navigation

Отримати приклад коду Get the sample code

Пов'язані статті Related articles

Вибір правильного елемента управління Is this the right control?
Вибір правильного елемента управління Is this the right control?
For example: ContentDialog subscribeDialog = new ContentDialog {Title = "Subscribe to App Service?
Провайдеры:
  • 08.09.2015

    Batyevka.NET предоставляет услуги доступа к сети Интернет на территории Соломенского района г. Киева.Наша миссия —... 
    Читать полностью

  • 08.09.2015
    IPNET

    Компания IPNET — это крупнейший оператор и технологический лидер на рынке телекоммуникаций Киева. Мы предоставляем... 
    Читать полностью

  • 08.09.2015
    Boryspil.Net

    Интернет-провайдер «Boryspil.net» начал свою работу в 2008 году и на данный момент является одним из крупнейших поставщиков... 
    Читать полностью

  • 08.09.2015
    4OKNET

    Наша компания работает в сфере телекоммуникационных услуг, а именно — предоставлении доступа в сеть интернет.Уже... 
    Читать полностью

  • 08.09.2015
    Телегруп

    ДП «Телегруп-Украина» – IT-компания с 15-летним опытом работы на рынке телекоммуникационных услуг, а также официальный... 
    Читать полностью

  • 08.09.2015
    Софтлинк

    Высокая скоростьМы являемся участником Украинского центра обмена трафиком (UA — IX) с включением 10 Гбит / сек... 
    Читать полностью