2016-03-23 3 views
1

Я установил значки в моей SecondaryCommand CommandBar, но не отображается. Зачем?Показать значок на SecondaryCommands (UWP)

<CommandBar RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignVerticalCenterWithPanel="True" Margin="0"> 
    <CommandBar.SecondaryCommands> 
    <AppBarButton Name="shareButton" Label="Condividi" x:Uid="condividi" Click="shareButton_Click" Icon="ReShare" /> 
    <AppBarButton Name="contactButton" Icon="Contact" x:Uid="contatti" Label="Contatti" Click="contactButton_Click" /> 
    </CommandBar.SecondaryCommands> 
</CommandBar> 

ответ

1

Не показаны из-за шаблона AppBarButton. Вам нужно будет изменить его.

Просто выполните следующие действия:

  1. Временно положить AppBarButton в CommandBar.PrimaryCommands коллекции.
  2. правой кнопкой мыши по кнопке в конструкторе и нажмите на Edit Template> Edit Копию ...
  3. В открывшемся диалоговом окне введите имя для вашего стиля, например, MyAppBarButtonStyle
  4. Установить этот стиль для ваших вторичных кнопок:

    <CommandBar.SecondaryCommands> 
        <AppBarButton Name="shareButton" Label="Condividi" x:Uid="condividi" Icon="ReShare" Style="{StaticResource MyAppBarButtonStyle}" /> 
        <AppBarButton Name="contactButton" Icon="Contact" x:Uid="contatti" Label="Contatti" Style="{StaticResource MyAppBarButtonStyle}" /> 
    </CommandBar.SecondaryCommands> 
    
  5. Изменить стиль по своему вкусу.

По умолчанию следующие elemnt используется в меню переполнения:

<TextBlock x:Name="OverflowTextLabel" Foreground="{TemplateBinding Foreground}" FontSize="15" FontFamily="{TemplateBinding FontFamily}" HorizontalAlignment="Stretch" Margin="12,0,12,0" Padding="0,5,0,7" TextAlignment="Left" TextWrapping="NoWrap" Text="{TemplateBinding Label}" TextTrimming="Clip" Visibility="Collapsed" VerticalAlignment="Center"/> 

Вы можете заменить его чем-то вроде этого:

<StackPanel x:Name="OverflowContentRoot" Orientation="Horizontal" Visibility="Collapsed" MinHeight="{ThemeResource AppBarThemeCompactHeight}"> 
    <ContentPresenter x:Name="OverflowContent" AutomationProperties.AccessibilityView="Raw" Content="{TemplateBinding Icon}" Foreground="{TemplateBinding Foreground}" HorizontalAlignment="Stretch" Height="20" Margin="0,14,0,4"/> 
    <TextBlock x:Name="OverflowTextLabel" Foreground="{TemplateBinding Foreground}" FontSize="15" FontFamily="{TemplateBinding FontFamily}" HorizontalAlignment="Stretch" Margin="12,0,12,0" Padding="0,5,0,7" TextAlignment="Left" TextWrapping="NoWrap" Text="{TemplateBinding Label}" TextTrimming="Clip" VerticalAlignment="Center"/> 
</StackPanel> 

Вам также нужно изменить визуальное состояние переполнения, чтобы отобразить ваш новый шаблон:

<VisualState x:Name="Overflow"> 
    <Storyboard> 
     <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="ContentRoot"> 
      <DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed"/> 
     </ObjectAnimationUsingKeyFrames> 
     <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="OverflowContentRoot"> 
      <DiscreteObjectKeyFrame KeyTime="0" Value="Visible"/> 
     </ObjectAnimationUsingKeyFrames> 
    </Storyboard> 
</VisualState> 

и увеличить ширину кнопки:

<Setter Property="Width" Value="150"/> 

Конечно, вы хотите, чтобы в дальнейшем изменить шаблон по своему вкусу, но это должно, по крайней мере, чтобы вы собираетесь.

+0

Спасибо вам за ответ! Работа! –

0

Ответ Дамира каким-то образом поставил меня на правильный путь и, потратив на это глупое количество времени, я в конце концов обнаружил решение, которое просто.

Обратите внимание, что он не может удовлетворить всех, как кнопки не получить подсвечиваются при наведении мышью, но это самый близкий и самый простой способ я понял, о том, как сделать это на UWP решение

Сначала определим ControlTemplate в вашем Styles.xaml или ваш Page.Resources как таковой:

<ControlTemplate x:Key="SecondaryCommandTemplate" TargetType="AppBarButton"> 
    <Grid x:Name="Root" Background="{TemplateBinding Background}"> 
     <Grid x:Name="ContentRoot" HorizontalAlignment="Stretch" Margin="5"> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="Auto" /> 
       <ColumnDefinition Width="*" /> 
      </Grid.ColumnDefinitions> 
      <ContentPresenter Grid.Column="0" VerticalContentAlignment="Center" 
      VerticalAlignment="Stretch" x:Name="Content" 
      AutomationProperties.AccessibilityView="Raw" Content="{TemplateBinding Icon}" 
      Foreground="{TemplateBinding Foreground}" HorizontalAlignment="Stretch" 
      Height="20" Margin="7,0,7,0"/> 
      <TextBlock Grid.Column="1" VerticalAlignment="Center" x:Name="TextLabel" 
      Foreground="{TemplateBinding Foreground}" FontSize="12" 
      FontFamily="{TemplateBinding FontFamily}" TextAlignment="Left" 
      TextWrapping="Wrap" Text="{TemplateBinding Label}"/> 
     </Grid> 
    </Grid> 
</ControlTemplate> 

Тогда просто определить Template ваш SecondaryCommands:

<CommandBar.SecondaryCommands> 
    <AppBarButton Label="Settings" 
        Icon="Setting" 
        Command="{Binding CommandBarViewModel.SettingsCommand}" 
        Template="{StaticResource SecondaryCommandTemplate}"/> 
    <AppBarButton Label="Admin" 
        Icon="Admin" 
        Command="{Binding CommandBarViewModel.SettingsCommand}" 
        Template="{StaticResource SecondaryCommandTemplate}"/> 
</CommandBar.SecondaryCommands> 

Это просто! То, чего я не понимаю, заключается в том, что после того, как после предложения Дамира и изучив стиль XAML, который был сгенерирован для кнопки, я закончил удаление всех визуальных состояний, и я заметил, что были отображены иконка и текст! Зачем?? Я не понимаю, почему Microsoft хочу скрыть значок в SecondaryCommands, и я буду честен, я не заметил конкретного кода, который на самом деле это сделал.Как только я удалил все VisualStates, я заметил, что меня оставили с шаблоном, а затем это был просто случай добавления сетки и игры с VerticalAlignment, HorizontalAlignment и «Margin».

Надеюсь, это поможет!

-1

Ну, это довольно просто, используйте ссылку microsoft.midiGmDls в своем проекте и все сделано.

0

Вот еще более простой, менее элегантный способ сделать это. Это работает, потому что большинство значков UWP являются глифами шрифта Segoe MDL2 Assets, включенным в Windows.

  1. Посмотрите точку Unicode для символа вы хотите от Microsoft's Segoe MDL2 Assets Guide (например. E702 для значка Bluetooth, E72D значок Share).
  2. Используйте что-то вроде UnicodeMap по показать это письмо на экране. Не беспокойтесь, что это выглядит как пустой квадрат , он будет работать в вашем приложении.
  3. Скопируйте персонаж в свой XAML, как показано ниже, убедившись, что FontFamily вашего AppBarButton настроен на Segoe MDL2 Assets.

<CommandBar.SecondaryCommands> <AppBarButton FontFamily="Segoe MDL2 Assets" Label=" Help"/> <AppBarButton FontFamily="Segoe MDL2 Assets" Label=" Update database"/> </CommandBar.SecondaryCommands>

И это то, что вы получите.

What this looks like when implemented

Я использую эту технику в приложении, которая локализуется на русском и китайском без проблем.

Смежные вопросы