Ugrás a tartalomhoz

.NET Programming Technologies

Gergely Kovásznai, Csaba Biró

Eszterházy Károly College

List-based controls

List-based controls

The list-based controls provide the well-known conventional services for us. The most important list-based controls (ListBox, ComboBox, TreeView, Menu, StatusBar, ToolBar).

ListBox

The ListBox control allows you to choose only one element by default.

V.9 Példa ListBox

<ListBox x:Name="Lista" SelectionMode="Extended">

            <ListBoxItem>Peach</ListBoxItem>

            <ListBoxItem>Apple</ListBoxItem>

            <ListBoxItem>Orange</ListBoxItem>

            <ListBoxItem>Lime</ListBoxItem>

</ListBox>

Key features:

  1. SelectedIndex – returns the index of the selected element (position in list)

  2. SelectedItem – the name of the selected item is returned

  3. IsSelected – it has a positive value if the current element is in an assigned state.

  4.  Single – allows you to select an item

  5. Multiple – allows you to select multiple items

  6. Extended – it is also allows you to select multiple items, but it provides option to choose listings which are not under each other with pressing the Ctrl button.

Example V.10 ListBox

V.8. ListBox

<StackPanel Orientation="Horizontal" VerticalAlignment="Top">

        <ListBox x:Name="List1" SelectionMode="Extended">

            <ListBoxItem>Peach</ListBoxItem>

            <ListBoxItem>Apple</ListBoxItem>

            <ListBoxItem>Orange</ListBoxItem>

            <ListBoxItem>Lime</ListBoxItem>

        </ListBox>

            <Button x:Name="sortButton" Width="50" Height="20" Margin="30"

                            Content="Sort" Click="sortButton _Click">

            </Button>

 </StackPanel>

Code-behind:

private void sortButton_Click(object sender, RoutedEventArgs e)

        {

            List1.Items.SortDescriptions.Add(new System.ComponentModel.SortDescription("Content",

       System.ComponentModel.ListSortDirection.Ascending ));

        }

ComboBox

The ComboBox is like LisBox, a drop-down list.

Example V.11 Példa ComboBox

<ComboBox x:Name="comboBox1" IsDropDownOpen="True">

            <ComboBoxItem>This</ComboBoxItem>

            <ComboBoxItem>is</ComboBoxItem>

            <ComboBoxItem>a</ComboBoxItem>

            <TextBlock>ComboBox!</TextBlock>

</ComboBox>

Example V.12 ComboBox

V.9. ComboBox

<StackPanel Orientation="Horizontal" VerticalAlignment="Top">

        <ComboBox Name="list1" Width="150" Height="30" Margin="0 0 5 0">

            <ComboBoxItem Content="Budapest"></ComboBoxItem>

            <ComboBoxItem Content="Eger"></ComboBoxItem>

            <ComboBoxItem Content="Füzesabony"></ComboBoxItem>

            <ComboBoxItem Content="Sopron"></ComboBoxItem>

            <ComboBoxItem Content="Kőszeg"></ComboBoxItem>

            <ComboBoxItem Content="Székesfehérvár"></ComboBoxItem>

        </ComboBox>

        <TextBox Name="tb1" Height="25" Width="150"/>

        <Button Name="addButton" Width="100" Height="25"

         Content="Add new city" Click="addButton_Click" Margin="5 0 5 0"/>

        <Button Name="deleteButton" Content="Delete city" Height="25"

         Width="100" Click="deleteButton_Click"/>

</StackPanel>

Code-behind:

      private void addButton_Click(object sender, RoutedEventArgs e)

        {

            list1.Items.Add(tb1.Text);

            tb1.Text = "";

        }

      private void deleteButton_Click(object sender, RoutedEventArgs e)

        {

            list1.Items.RemoveAt

            (list1.Items.IndexOf(list1.SelectedItem));

}

TreeWiew

The TreeView control elements can be arranged hierarchically. It is ItemsControl too, nodes may contain not the text only. Type of the elements: TreeViewItem from the HeaderedItemsControl class. Each item has a Header feature, could be set the label of each elements with the help of it.

Example V.13 TreeView

<TreeView>

       <TreeViewItem Header="Female names:">

           <TreeViewItem Header="Éva"/>

           <TreeViewItem Header="Krisztina"/>

           <TreeViewItem Header="Mária"/>

       </TreeViewItem>

       <TreeViewItem Header="Male names">

           <TreeViewItem Header="Gábor"/>

           <TreeViewItem Header="Áron"/>

           <TreeViewItem Header="Csaba"/>

      </TreeViewItem>

</TreeView>

V.10. TreeView

<TreeView Name="tv" ItemsSource="{Binding}">

            <TreeView.ItemTemplate>

                <HierarchicalDataTemplate ItemsSource="{Binding Path=Folders}">

                    <StackPanel Orientation="Horizontal">

                       <Image Source="Icons/advanced_directory.ico" Width="20" 

                         Height="20" Margin="0 0 5 0"/>

                       <TextBlock Text="{Binding Path=Name}" FontSize="16" />  

                    </StackPanel>  

                </HierarchicalDataTemplate>

            </TreeView.ItemTemplate>

</TreeView>

Code-behind:

public class Folder

{

    public string Name

    {

        get

        {

            if (!String.IsNullOrEmpty(Path))

            {

                return System.IO.Path.GetFileName(Path);

            }

            return null;

        }

    }

    public string Path

    { get; set; }

    public List<Folder> Folders

    { get; set; }

    public Folder()

    {

        Folders = new List<Folder>();

    }

    public static Folder CreateFolderTree(string rootFolder)

    {

        Folder fld = new Folder { Path = rootFolder };

        foreach (var item in Directory.GetDirectories(rootFolder))

        {

            fld.Folders.Add(CreateFolderTree(item));

        }

        return fld;

    }

}

public partial class MainWindow : Window

{

    public MainWindow()

    {

        InitializeComponent();

        List<Folder> folders = new List<Folder>();

        folders.Add(Folder.CreateFolderTree(@"C:\WPFTree"));

        tv.DataContext = folders;

    }

}

Menu

In WPF applications you can create menus easily. This is very important, as the Menu control is necessary in most of the applications. The menu allows the hierarchical arrangement of the most commonly used commands.

Key features:

Command – you can set commands for the individual menu items

Header – allows you to adjust the text on the menu items

Icon – it can be assigned to individual menu items

IsChecked -  set or queried whether each item is checked

IsEnabled – set or queried whether each option is enabled

Example V.14 Menu

V.11. Menu

<Menu Height="25" VerticalAlignment="Top">

        <MenuItem Header="_File">

           <MenuItem Header="_New" InputGestureText="Ctrl+N">

              <MenuItem.ToolTip>

                   <ToolTip>

                      New document

                   </ToolTip>

              </MenuItem.ToolTip>

              <MenuItem.Icon>

                   <Image Width="20" Height="20" Source="Icons/application.png" />

              </MenuItem.Icon>

              <MenuItem Header="_Project..."/>

              <MenuItem Header="_Web Site..."/>

              </MenuItem>

              <MenuItem Header="_Open"

                      Command="ApplicationCommands.Open">

                 <MenuItem.Icon>

                     <Image Width="20" Height="20" Source="Icons/page.png" />

                 </MenuItem.Icon>

              </MenuItem>

              <MenuItem Header="_Save"

                       Command="ApplicationCommands.Save">

                  <MenuItem.Icon>

                     <Image Width="20" Height="20" Source="Icons/disk.png" />

                  </MenuItem.Icon>

              </MenuItem>

              <MenuItem Header="Save _As">

                  <MenuItem.Icon>

                     <Image Width="20" Height="20" Source="Icons/disk_multiple.png" />

                  </MenuItem.Icon>

              </MenuItem>

              <Separator/>

              <MenuItem Header="_Print">

                 <MenuItem.Icon>

                     <Image Width="20" Height="20" Source="Icons/printer.png" />

                  </MenuItem.Icon>

              </MenuItem>

              <MenuItem Header="Exit" Click="exit_Click"/>

          </MenuItem>

          <MenuItem Header="_Edit">

              <MenuItem Header="_Undo"/>

              <MenuItem Header="_Cut"/>

              <MenuItem Header="_Copy"

                       Command="ApplicationCommands.Copy"/>

              <MenuItem Header="_Paste"/>

          </MenuItem>

         <MenuItem Header="Help">

             <MenuItem Header="Program"  Click="program_Click"/>

        </MenuItem>

</Menu>

We can assign Click events for the individual members of the Menu class, like in the Button one.

Code-behind:

private void exit_Click(object sender, RoutedEventArgs e)

{

        Application.Current.Shutdown();

}

private void program_Click(object sender, RoutedEventArgs e)

{

         MessageBox.Show(".Net Programming Technologies");

}

ToolBar

With the help of toolbars we can take the interface of our application userfriendly.

Example V.15 ToolBar 1

<ToolBarTray>

            <ToolBar>

                <Button ToolTip="Open" Command="ApplicationCommands.Open">

                    <Image Source="Icons/folder_page.png" />

                </Button>

                <Button ToolTip="Save" Command="ApplicationCommands.Save">

                    <Image Source="Icons/disk.png" />

                </Button>

                <Button ToolTip="Save As" Command="ApplicationCommands.SaveAs">

                    <Image Source="Icons/disk_multiple.png" />

                </Button>

            </ToolBar>

</ToolBarTray>

Example V.16 ToolBar 2

V.12. ToolBar

<ToolBar>

       <ToggleButton x:Name="bold" ToolTip="Bold"

                     Command="EditingCommands.ToggleBold">

                    <Image Source="Icons/text_bold.png" />

       </ToggleButton>

       <ToggleButton x:Name="italic" ToolTip="Italic" 

                     Command="EditingCommands.ToggleItalic">

                   <Image Source="Icons/text_italic.png" />

       </ToggleButton>

       <ToggleButton ToolTip="Underline" x:Name="underline"

                     Command="EditingCommands.ToggleUnderline">

                  <Image Source="Icons/text_underline.png" />

       </ToggleButton>

       <ComboBox x:Name="sizeT" Width="30" />

</ToolBar>

Code-behind:

     private void Window_Loaded(object sender, RoutedEventArgs e)

     {

        for (double i = 8; i < 90; i += 2)

         {

           sizeT.Items.Add(i);

         }

     }

     private void SetFontSize(double size)

     {

        sizeT.SelectedValue = size;

     }

     private void SetFontWeight(FontWeight weight

     {

        bold.IsChecked = weight == FontWeights.Bold;

     }

     private void SetFontStyle(FontStyle style)

     {

        italic.IsChecked = style == FontStyles.Italic;

     }

     private void SetTextDecoration(TextDecorationCollection decoration)

     {

        underline.IsChecked = decoration == TextDecorations.Underline;

     }

StatusBar

StatusBar is very similar to the previously known toolbar. Variety of information can be written on the bottom of the application window for users. For example, in a graphics editor we can write the mouse coordinates, the coordinates of the selected part, size, line width, the current font, etc.

Example V.17 StatusBar

V.13. StatusBar

<StatusBar VerticalAlignment="Bottom" Background="Beige" >

            <StatusBarItem>

                <TextBlock>Letöltés</TextBlock>

            </StatusBarItem>

            <StatusBarItem>

                <ProgressBar Width="100" Height="20" Name="pb"  >

                    <ProgressBar.Triggers>

                        <EventTrigger RoutedEvent="Window.Loaded">

                            <BeginStoryboard>

                                <Storyboard>

                                    <DoubleAnimation

                                       Storyboard.TargetName="pb"

                                       Storyboard.TargetProperty="Value"

                                       From="0" To="100" Duration="0:0:5" />

                                    <ColorAnimation

                                       Storyboard.TargetName="dlE"

                                       Storyboard.TargetProperty="Fill.Color"

                                       From="Green" To="Red"

                                       Duration="0:0:5" />

                                </Storyboard>

                            </BeginStoryboard>

                        </EventTrigger>

                    </ProgressBar.Triggers>

                </ProgressBar>

            </StatusBarItem>

            <Separator/>

            <StatusBarItem>

              <TextBlock Text="{Binding ElementName=pb, Path=Value, StringFormat=0}"/>

            </StatusBarItem>

            <StatusBarItem>

                <TextBlock Text="%"/>

            </StatusBarItem>

            <StatusBarItem>

                <Ellipse x:Name="dlE" Fill="Green" Height="10" Width="10"/>

            </StatusBarItem>

            <Separator/>

            <StatusBarItem>

                <TextBlock x:Name="tb">Állapotsor</TextBlock>

            </StatusBarItem>

            <Separator/>

            <StatusBarItem >

                <Image Source="Images\help.png" Width="16" Height="16"

                       ToolTip="Segítség"/>

            </StatusBarItem>

            <StatusBarItem HorizontalAlignment="Right">

                <TextBlock x:Name="idoTb" />

            </StatusBarItem>

</StatusBar>

Code-behind:

namespace StatusBar

{

    /// <summary>

    /// Interaction logic for MainWindow.xaml

    /// </summary>

    public partial class MainWindow : Window

    {

        DispatcherTimer ido;

        StringBuilder stb;

        void Initialize()

        {

            ido = new DispatcherTimer();

            ido.Interval = TimeSpan.FromSeconds(1.0);

            ido.Start();

            stb = new StringBuilder();

            ido.Tick += new EventHandler(delegate(object s, EventArgs a)

            {

                stb.Clear();

                if (DateTime.Now.Hour < 10) stb.Append(0);

                stb.Append(DateTime.Now.Hour);

                stb.Append(':');

                if (DateTime.Now.Minute < 10) stb.Append(0);

                stb.Append(DateTime.Now.Minute);

                stb.Append(':');

                if (DateTime.Now.Second < 10) stb.Append(0);

                stb.Append(DateTime.Now.Second);

                idoTb.Text = stb.ToString();

            });

        }

        public MainWindow()

        {

            Initialize();

            InitializeComponent();

        }

    }

}