Controle ToolBar no WPF

Em WPF, os controles ToolBarTray e ToolBar são usados juntos para criar contêineres de barra de ferramentas.

O ToolBarTray pode conter múltiplos ToolBars, e as propriedades Band e BandIndex controlam o layout dos ToolBars dentro do ToolBarTray.

Propriedades Band e BandIndex

Band: Representa o índice da linha (ou faixa) onde o ToolBar está posicionado no ToolBarTray. O índice da faixa começa em 0, e ToolBars com o mesmo valor de Band são exibidos na mesma linha.

BandIndex: Define a ordem de exibição dos ToolBars dentro do mesmo Band (linha). Quanto menor o valor de BandIndex, mais à esquerda (ou anterior) o ToolBar será posicionado.

Detalhamento das propriedades Band e BandIndex do ToolBar do WPF

As propriedades Band e BandIndex são dois atributos cruciais para o layout do ToolBar dentro do ToolBarTray, determinando conjuntamente a posição e a ordem de排列 das barras de ferramentsa.

Conceitos Fundamentais

Propriedade Band

  • Função: Define a linha (faixa) onde a barra de ferramentas será posicionada
  • Tipo: int
  • Valor padrão: 0
  • Descrição: Barras de ferramentas com o mesmo valor de Band serão exibidas na mesma linha

Propriedade BandIndex

  • Função: Define a ordem de exibição dentro do mesmo Band (linha)
  • Tipo: int
  • Valor padrão: 0
  • Descrição: Barras de ferramentas com menor valor de BandIndex aparecerão à esquerda

Exemplo Prático

<Window x:Class="ExemploToolBar.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Exemplo de Band e BandIndex" Height="400" Width="600">
    
    <DockPanel>
        <ToolBarTray DockPanel.Dock="Top" Background="LightBlue">
            
            <!-- Primeira linha de barras de ferramentas -->
            <ToolBar Band="0" BandIndex="0" Background="LightYellow">
                <Label Content="Band=0, BandIndex=0" FontWeight="Bold"/>
                <Button Content="Arquivo"/>
                <Button Content="Editar"/>
                <Button Content="Exibir"/>
            </ToolBar>
            
            <ToolBar Band="0" BandIndex="1" Background="LightGreen">
                <Label Content="Band=0, BandIndex=1" FontWeight="Bold"/>
                <Button Content="Ferramentas"/>
                <Button Content="Janelas"/>
                <Button Content="Ajuda"/>
            </ToolBar>
            
            <ToolBar Band="0" BandIndex="2" Background="LightCoral">
                <Label Content="Band=0, BandIndex=2" FontWeight="Bold"/>
                <Button Content="Configurações"/>
                <Button Content="Sobre"/>
            </ToolBar>
            
            <!-- Segunda linha de barras de ferramentas -->
            <ToolBar Band="1" BandIndex="0" Background="LightPink">
                <Label Content="Band=1, BandIndex=0" FontWeight="Bold"/>
                <Button Content="Novo"/>
                <Button Content="Abrir"/>
                <Button Content="Salvar"/>
            </ToolBar>
            
            <ToolBar Band="1" BandIndex="1" Background="LightSeaGreen">
                <Label Content="Band=1, BandIndex=1" FontWeight="Bold"/>
                <Button Content="Copiar"/>
                <Button Content="Recortar"/>
                <Button Content="Colar"/>
            </ToolBar>
            
            <!-- Terceira linha de barras de ferramentas -->
            <ToolBar Band="2" BandIndex="0" Background="LightGoldenrodYellow">
                <Label Content="Band=2, BandIndex=0" FontWeight="Bold"/>
                <Button Content="Negrito"/>
                <Button Content="Itálico"/>
                <Button Content="Sublinhado"/>
            </ToolBar>
            
        </ToolBarTray>
        
        <Grid>
            <TextBlock Text="Observe a disposição das barras de ferramentas com diferentes Band e BandIndex" 
                      HorizontalAlignment="Center" VerticalAlignment="Center"
                      FontSize="16" TextAlignment="Center"/>
        </Grid>
    </DockPanel>
</Window>


Detalhes das Regras de Layout

1. Arranjo dentro do mesmo Band

<!-- Essas três barras estão na linha Band=0 -->
<ToolBar Band="0" BandIndex="0">...à esquerda...</ToolBar>
<ToolBar Band="0" BandIndex="1">...no meio...</ToolBar>
<ToolBar Band="0" BandIndex="2">...à direita...</ToolBar>


2. Arranjo entre Bands diferentes

<!-- Três linhas de barras de ferramentas de cima para baixo -->
<ToolBar Band="0" BandIndex="0">Primeira linha</ToolBar>
<ToolBar Band="1" BandIndex="0">Segunda linha</ToolBar>
<ToolBar Band="2" BandIndex="0">Terceira linha</ToolBar>


Exemplo de Ajuste Dinâmico

<Window x:Class="ExemploDinamico.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Exemplo de Ajuste Dinâmico de Band" Height="500" Width="700">
    
    <Window.Resources>
        <Style TargetType="ToolBar">
            <Setter Property="Background" Value="#F0F8FF"/>
            <Setter Property="Margin" Value="2"/>
        </Style>
    </Window.Resources>
    
    <DockPanel>
        <!-- Painel de controle -->
        <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" 
                   Background="White" Height="40">
            <TextBlock Text="Ajustar Band e BandIndex:" VerticalAlignment="Center" Margin="10,0"/>
            <ComboBox x:Name="ComboBand" Width="80" Margin="5" 
                     SelectionChanged="ComboBand_SelectionChanged">
                <ComboBoxItem Content="0"/>
                <ComboBoxItem Content="1"/>
                <ComboBoxItem Content="2"/>
            </ComboBox>
            <ComboBox x:Name="ComboBandIndex" Width="80" Margin="5"
                     SelectionChanged="ComboBandIndex_SelectionChanged">
                <ComboBoxItem Content="0"/>
                <ComboBoxItem Content="1"/>
                <ComboBoxItem Content="2"/>
            </ComboBox>
            <Button Content="Redefinir layout" Click="RedefinirLayout_Click" Margin="10" Padding="10,5"/>
        </StackPanel>
        
        <!-- Área das barras de ferramentas -->
        <ToolBarTray DockPanel.Dock="Top" Name="PainelPrincipal" Background="White">
            
            <ToolBar Name="BarraFerramentas1" Band="0" BandIndex="0">
                <Label Content="Barra 1" FontWeight="Bold" Foreground="DarkBlue"/>
                <Button Content="Novo"/>
                <Button Content="Abrir"/>
                <Button Content="Salvar"/>
            </ToolBar>
            
            <ToolBar Name="BarraFerramentas2" Band="0" BandIndex="1">
                <Label Content="Barra 2" FontWeight="Bold" Foreground="DarkGreen"/>
                <Button Content="Copiar"/>
                <Button Content="Recortar"/>
                <Button Content="Colar"/>
            </ToolBar>
            
            <ToolBar Name="BarraFerramentas3" Band="1" BandIndex="0">
                <Label Content="Barra 3" FontWeight="Bold" Foreground="DarkRed"/>
                <Button Content="Negrito"/>
                <Button Content="Itálico"/>
                <Button Content="Sublinhado"/>
            </ToolBar>
            
        </ToolBarTray>
        
        <!-- Exibição de status -->
        <Grid>
            <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
                <TextBlock x:Name="TextoStatus" FontSize="14" TextAlignment="Center" 
                          TextWrapping="Wrap" Margin="20"/>
                <TextBlock Text="Estado atual do layout:" FontWeight="Bold" Margin="0,10,0,5"/>
                <TextBlock x:Name="TextoInformacoesLayout" TextAlignment="Center"/>
            </StackPanel>
        </Grid>
    </DockPanel>
</Window>


Código C# correspondente:

using System.Windows;
using System.Windows.Controls;

namespace ExemploDinamico
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            AtualizarInformacoesLayout();
            ComboBand.SelectedIndex = 0;
            ComboBandIndex.SelectedIndex = 0;
        }
        
        private void ComboBand_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (BarraFerramentas1 != null && ComboBand.SelectedItem is ComboBoxItem item)
            {
                int banda = int.Parse(item.Content.ToString());
                BarraFerramentas1.Band = banda;
                AtualizarInformacoesLayout();
            }
        }
        
        private void ComboBandIndex_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (BarraFerramentas1 != null && ComboBandIndex.SelectedItem is ComboBoxItem item)
            {
                int indiceBanda = int.Parse(item.Content.ToString());
                BarraFerramentas1.BandIndex = indiceBanda;
                AtualizarInformacoesLayout();
            }
        }
        
        private void RedefinirLayout_Click(object sender, RoutedEventArgs e)
        {
            BarraFerramentas1.Band = 0;
            BarraFerramentas1.BandIndex = 0;
            BarraFerramentas2.Band = 0;
            BarraFerramentas2.BandIndex = 1;
            BarraFerramentas3.Band = 1;
            BarraFerramentas3.BandIndex = 0;
            
            ComboBand.SelectedIndex = 0;
            ComboBandIndex.SelectedIndex = 0;
            AtualizarInformacoesLayout();
        }
        
        private void AtualizarInformacoesLayout()
        {
            if (BarraFerramentas1 != null)
            {
                TextoStatus.Text = $"Barra 1: Band={BarraFerramentas1.Band}, BandIndex={BarraFerramentas1.BandIndex}";
                
                TextoInformacoesLayout.Text = $"Barra 1: Band={BarraFerramentas1.Band}, BandIndex={BarraFerramentas1.BandIndex}\n" +
                                            $"Barra 2: Band={BarraFerramentas2.Band}, BandIndex={BarraFerramentas2.BandIndex}\n" +
                                            $"Barra 3: Band={BarraFerramentas3.Band}, BandIndex={BarraFerramentas3.BandIndex}";
            }
        }
    }
}


Cenários de Aplicação Prática

Cenário 1: Agrupamento de barras de ferramentas

<ToolBarTray>
    <!-- Grupo de operações de arquivo -->
    <ToolBar Band="0" BandIndex="0">
        <TextBlock Text="Arquivo:" FontWeight="Bold" Margin="5,0"/>
        <Button Content="Novo"/>
        <Button Content="Abrir"/>
        <Button Content="Salvar"/>
    </ToolBar>
    
    <!-- Grupo de operações de edição -->
    <ToolBar Band="0" BandIndex="1">
        <TextBlock Text="Editar:" FontWeight="Bold" Margin="5,0"/>
        <Button Content="Copiar"/>
        <Button Content="Recortar"/>
        <Button Content="Colar"/>
    </ToolBar>
    
    <!-- Grupo de operações de formatação -->
    <ToolBar Band="1" BandIndex="0">
        <TextBlock Text="Formatar:" FontWeight="Bold" Margin="5,0"/>
        <Button Content="Negrito"/>
        <Button Content="Itálico"/>
        <Button Content="Sublinhado"/>
    </ToolBar>
</ToolBarTray>


Cenário 2: Layout responsivo de barras de ferramentas

<ToolBarTray>
    <!-- Funcionalidades principais -->
    <ToolBar Band="0" BandIndex="0">
        <Button Content="Func. principal 1"/>
        <Button Content="Func. principal 2"/>
    </ToolBar>
    
    <!-- Funcionalidades secundárias -->
    <ToolBar Band="0" BandIndex="1">
        <Button Content="Func. secundária 1"/>
        <Button Content="Func. secundária 2"/>
    </ToolBar>
    
    <!-- Funcionalidades estendidas (podem ser ocultas em telas pequenas) -->
    <ToolBar Band="1" BandIndex="0" x:Name="BarraFerramentasEstendida">
        <Button Content="Func. estendida 1"/>
        <Button Content="Func. estendida 2"/>
    </ToolBar>
</ToolBarTray>


Observações Importantes

  1. Valores de Band podem ser não consecutiovs: Não é necessário que os valores de Band sejam sequenciais; pode haver Band=0 e Band=2 sem Band=1
  2. BandIndex determina a ordem na mesma linha: Dentro do mesmo Band, valores menores de BandIndex ficam à esquerda, maiores à direita
  3. Ajuste pelo usuário: Usuários podem arrastar barras de ferramentas durante a execução para alterar seus Band e BandIndex
  4. Tratamento de Band vazios: Se um Band não contiver nenhuma barra de ferramentas, essa linha não será exibida
  5. Considerações de performance: Valores de Band muito altos criam muitas linhas vazias, o que pode afetar o desempenho

Tags: WPF ToolBar ToolBarTray Band BandIndex

Publicado em 6-30 23:44