6. WPF control

Source: Internet
Author: User

WPF controls:

  • Content Control
  • Title Content Control
  • Text Control
  • List controls
  • Range-based controls
  • Date Control
Controls

Controls are elements that interact with users. Controls can get focus and can accept input from the keyboard or mouse.

The base class of all controls is the System. Windows. Control class, which includes some basic functions:

  • Alignment
  • Tab Sequence
  • Background, prospects, and Boundaries
  • Text font
Background and foreground brushes

The control includes two attributes: Background and Foreground, which use a Brush object. The derived classes of the brush object include the SolidColorBrush, LinearGradientBrush, and TileBrush classes.

Set color with code

Set the background color for the button named cmd:

cmd.Background = new SolidColorBrush(Colors.AliceBlue);

Obtain the predefined color through the static attribute of the Colors class, pass it to the constructor to create a new SolidColorBrush instance, and assign it to the background attribute of the button.

You can also use the system color:

cmd.Background = new SolidColorBrush(SystemColors.ControlColor);

The SystemColors class also provides pre-fabricated attributes to return the SolidColorBrush object:

cmd.Background = SystemColors.ControlBrush;

You can create a color object by providing R, G, and B values (red, green, and blue ). Each value is a number ranging from 0 to 255:

int red = 0; int green = 255; int blue = 0;cmd.Foreground = new SolidColorBrush(Color.FromRgb(red, green, blue));

You can set the Color transparency by calling the Color. FromArgb () method to pass the alpha value to it. If the alpha value is 255, it is completely opaque, and if it is 0, it is completely transparent.

Set color with XAML

In XAML, you only need to provide the color name or color value. The parser is responsible for other work.

<Button Background="Red">A Button</Button>

The color value is provided in the format of # rrggbb or # 20.rggbb:

<Button Background="#FFFF0000">A Button</Button>

The brush supports automatic change notifications. The brush is derived from the System. Windows. Freezable class. The Freezable class has two states: readable and read-only (frozen)

The control class also defines the BorderBrush and BorderThickness attributes.

Font

The Control class defines several font-related attributes. Determines the appearance of the control text. These attributes are listed in Table 6-1.

Name Description
FontFamily  
FontSize  
FontStyle  
FontWeight  
FontStretch  

The Control class does not define any attributes that use its font. However, many controls include the Text attribute and are not defined as members of the Control base class. Obviously, the font attribute is meaningless unless used by the derived class.

Font family

 

Mouse cursor Content Control

A content control is a special control type that can own and display a piece of content. Technically, content control is a control that can contain a single nested element. The difference between a content control and a layout container is that a content control can contain only one child element, while a layout container can have any child element.

Of course, you can still wrap multiple contents into the content control. The trick is to wrap them all in a single container, such as a StackPanel or a Grid. For example, the Window class is a content control. Obviously, Windows often have a lot of content, but they are all wrapped in a top-layer container (typically, Grid ).

All content controls originate from the ContentControl abstract class. The content control class mainly includes some public controls Label and ToolTip. Various Button controls: Button, RadioButton, and CheckBox. Some more dedicated ScrollViewer and UserControl. Window itself is a content control.

Finally, there is a subset of content controls, which is derived from the HeaderedContentControl class and adds an inheritance layer. Includes GroupBox, TabItem, and Expander controls. These controls have content areas and title areas, which are used to display certain titles.

In addition, the Frame used for navigation, the ListBoxItem and StatusBarItem used in other controls are also content controls.

Content Attributes

The ContentControl class adds a Content attribute and accepts a single object. The Content attribute supports any type of object, but it divides the object into two groups and treats them differently:

  • Objects not derived from UIElement: The content control calls ToString () to obtain the text of these controls and then displays the text.
  • Objects derived from UIElement: these objects include all visual elements. Use the UIElement. OnRender () method to display it inside the content control.

For example, a button that provides a simple string:

<Button Margin="3">Text content</Button>

Use the Image class to place an Image in the button:

<Button Margin="3">  <Image Source="happyface.jpg" Stretch="None" /></Button>

Place a container for the wrapped image and text in the button:

<Button Margin="3">  <StackPanel>    <TextBlock Margin="3">Image and text button</TextBlock>    <Image Source="happyface.jpg" Stretch="None" />    <TextBlock Margin="3">Courtesy of the StackPanel</TextBlock>  </StackPanel></Button>

You can even place other content controls in the buttons, such as text boxes, buttons, and combo boxes. Although this is not reasonable, WPF allows this.

Window is a content control, but it can only be a top-level container and cannot be nested in other elements.

Other attributes of the content control include:

HasContent attribute. If it is true, the control has content.

The ContentTemplate attribute is a template that tells the control how to display objects. Use ContentTemplate to intelligently display non-UIElement derived objects. You can get various attribute values of an object and put them into more complex tags.

Align content

The HorizontalContentAlignment and VerticalContentAlignment values are Top, Bottom, Left, Right, Center, and Stretch.

The Padding attribute refers to the distance between the control boundary and its content.

HorizontalContentAlignment, VerticalContentAlignment, and Padding attributes are defined in the Control class, not in the special ContentControl class. Because some controls that are not content controls also have some content. For example, TextBox is not a content control and uses the preceding property to set the input text.

WPF content Philosophy

Content controls reduce the number of controls, but increase the complexity of controls.

Label)

The main function of the tag control is to enable the Link Control to get the focus shortcut key. The Target attribute of the tag control specifies the Link Control. To set the Target, use the binding expression to point to another control.

<Label Target="{Binding ElementName=txtA}">Choose _A</Label><TextBox Name="txtA"></TextBox><Label Target="{Binding ElementName=txtB}">Choose _B</Label><TextBox Name="txtB"></TextBox>

The label Text underline specifies the shortcut key. If you really need an underline, you can enter two underline escape characters in a row.

At the same time, press Alt and the specified shortcut key, and the linked control will get the focus. For example, in this example, press Alt + A and the focus will jump to the txtA control.

You can use TextBlock if you do not need the mnk function.

Button controls

Buttons include buttons, CheckBox, and RadioButton. They are all derived from ButtonBase.

Click supports command functions.

ClickMode attribute, ClickMode. Release, ClickMode. Press, ClickMode. Hover

Shortcut Keys are also supported.

Button

Each window can have the cancel button and default button. You can set the IsCancel and IsDefault attributes of the button. For details, refer to page 159.

In addition, there is a confusing IsDefaulted attribute, as shown on the side of page 160.

ToggleButton, RepeatButton

There are three classes derived from ButtonBase:

  • GridViewColumnHeader
  • RepeatButton
  • ToggleButton

Both RepeatButton and ToggleButton are located in the System. Windows. Controls. Primitives namespace. It is often used to combine or derive from other controls. It can also be used independently.

CheckBox

Both CheckBox and RadioButton are derived from ToggleButton.

ToggleButton adds an IsChecked attribute, which is an empty Boolean value.

To assign a null value to the WPF tag, use the empty tag extension as follows:

<CheckBox IsChecked="{x:Null}">A check box in indeterminate state</CheckBox>

ToggleButton also has an IsThreeState attribute, which determines whether the check box can be set to uncertain state. The default value is false.

The ToggleButton class defines three events: Checked, Unchecked, and Indeterminate events.

RadioButton

By default, single-choice buttons are grouped by their containers. The GroupName attribute of RadioButton allows you to overwrite this behavior.

<StackPanel>  <GroupBox Margin="5">    <StackPanel>      <RadioButton>Group 1</RadioButton>      <RadioButton>Group 1</RadioButton>      <RadioButton>Group 1</RadioButton>      <RadioButton Margin="0,10,0,0" GroupName="Group2">Group 2</RadioButton>    </StackPanel>  </GroupBox>  <GroupBox Margin="5">    <StackPanel>      <RadioButton>Group 3</RadioButton>      <RadioButton>Group 3</RadioButton>      <RadioButton>Group 3</RadioButton>      <RadioButton Margin="0,10,0,0" GroupName="Group2">Group 2</RadioButton>    </StackPanel>  </GroupBox></StackPanel>

The GroupBox container does not need to wrap single-choice button groups, but this is a general convention. GroupBox displays a boundary and a title.

Dedicated container

The content control also includes some specialized containers.

ScrollViewer inherits directly from ContentControl.

The ContentControl class derives from the HeaderedContentControl class, which includes a title and a content. The title and content can be nested with a single child element. The HeaderedContentControl class derives from several subclasses: GroupBox, TabItem, and Expander.

ScrollViewer

Although ScrollViewer can wrap any element, it typically wraps a layout container.

<ScrollViewer>  <Grid Margin="3,3,10,3">  </Grid></ScrollViewer>

VerticalScrollBarVisibility attribute, which is the ScrollBarVisibility enumeration. Visible, Auto, and Disabled. The default value is Visible.

HorizontalScrollBarVisibility. The default value is Hidden.

Programming Control scroll

For details, refer to page 171.

Custom scrolling

For details, refer to page 172.

GroupBox

GroupBox is derived from the HeaderedContentControl class.

<GroupBox Header="A GroupBox Test" Padding="5"  Margin="5" VerticalAlignment="Top">  <StackPanel>    <RadioButton Margin="3">One</RadioButton>    <RadioButton Margin="3">Two</RadioButton>    <RadioButton Margin="3">Three</RadioButton>    <Button Margin="3">Save</Button>  </StackPanel></GroupBox>

GroupBox still requires a layout container. GroupBox does not have any special functions, but it is just a decoration control.

TabItem

TabItem represents a tab of TabControl. The IsSelected attribute is added to the TabItem class, indicating whether the tab is the tab currently displayed by TabControl.

<TabControl Margin="5">  <TabItem Header="Tab One">    <StackPanel Margin="3">      <CheckBox Margin="3">Setting One</CheckBox>      <CheckBox Margin="3">Setting Two</CheckBox>      <CheckBox Margin="3">Setting Three</CheckBox>    </StackPanel>  </TabItem>  <TabItem Header="Tab Two">    ...  </TabItem></TabControl>

You can set the TabStripPlacement attribute of TabControl to move the tab from the top to the side.

Just like the Content attribute, the Header attribute can accept any type of objects. This is an example:

<TabControl Margin="5">  <TabItem>    <TabItem.Header>      <StackPanel>        <TextBlock Margin="3" >Image and Text Tab Title</TextBlock>        <Image Source="happyface.jpg" Stretch="None" />      </StackPanel>    </TabItem.Header>    <StackPanel Margin="3">      <CheckBox Margin="3">Setting One</CheckBox>      <CheckBox Margin="3">Setting Two</CheckBox>      <CheckBox Margin="3">Setting Three</CheckBox>    </StackPanel>  </TabItem>  <TabItem Header="Tab Two"></TabItem></TabControl>
Expander

For details, see page 175.

Text Control

WPF includes three text input controls: TextBox, RichTextBox, and PasswordBox. PasswordBox is derived directly from Control. The TextBox and RichTextBox controls are derived from TextBoxBase.

Unlike content controls, text boxes are limited to the types of content they can contain. TextBox always stores a string (Text attribute ). PasswordBox also processes string content (Password attribute), although it uses SecureString. Only RichTextBox can store more sophisticated content: A FlowDocument.

Multi-Line Text

Set the maximum number of characters allowed by TextBox.

Set the TextWrapping attribute to Wrap or WrapWithOverflow, which indicates automatic line feed.

MinLines and MaxLines attributes, set the minimum (maximum) number of lines visible to TextBox.

LineCount attribute to retrieve the number of lines of text in the text box.

VerticalScrollBarVisibility and HorizontalScrollBarVisibility attributes to set the visible status of the scroll bar.

The AcceptsReturn attribute. If it is set to true, TextBox accepts carriage return. By default, TextBox does not accept carriage return.

If the AcceptsTab attribute is true, the Tab key is accepted. By default, the Tab key is not accepted in TextBox.

The IsReadOnly attribute prevents text editing.

Text Selection

For details, see page 180.

Spelling check

For details, see page 181.

Password box

For details, see page 183.

List controls

The base class of the list control is the ItemsControl class.

Each ItemsControl class has a project list. There are two ways to fill in the project list. The most straightforward method is to add items directly to the item set and use code or XAML. A more common method is data binding. This method sets the ItemsSource attribute to the data set to be displayed.

One of the main branches derived from the ItemsControl class is the Selector class, including The ListBox, ComboBox, and TabControl classes. You can track the current SelectedItem or its position (SelectedIndex ).

The remaining List classes do not support the current item and are derived directly from the ItemsControl class. These classes include Menu, Toolbar, and TreeView.

ListBox

You can set the SelectionMode attribute to Multiple. In the multiple-choice mode, you must use the SelectedItems set instead of SelectedItem.

Add a list item:

<ListBox>  <ListBoxItem>Green</ListBoxItem>  <ListBoxItem>Blue</ListBoxItem>  <ListBoxItem>Yellow</ListBoxItem>  <ListBoxItem>Red</ListBoxItem></ListBox>

ListBoxItem is derived from ContentControl.

For example, create a list box for the image:

<ListBox>  <ListBoxItem>    <Image Source="happyface.jpg"></Image>  </ListBoxItem>  <ListBoxItem>    <Image Source="happyface.jpg"></Image>  </ListBoxItem></ListBox>

The ListBoxItem in the preceding example can be omitted. The ListBoxItem in the list box is smart enough to identify the list items:

<ListBox>  <StackPanel Orientation="Horizontal">    <Image Source="happyface.jpg"  Width="30" Height="30"></Image>    <Label VerticalContentAlignment="Center">A happy face</Label>  </StackPanel>    <StackPanel Orientation="Horizontal">    <Image Source="redx.jpg" Width="30" Height="30"></Image>    <Label VerticalContentAlignment="Center">A warning sign</Label>  </StackPanel>    <StackPanel Orientation="Horizontal">    <Image Source="happyface.jpg"  Width="30" Height="30"></Image>    <Label VerticalContentAlignment="Center">A happy face</Label>  </StackPanel></ListBox>

The following is an example of a check box for a list item:

<ListBox Name="lst" SelectionChanged="lst_SelectionChanged"  CheckBox.Click="lst_SelectionChanged">  <CheckBox Margin="3">Option 1</CheckBox>  <CheckBox Margin="3">Option 2</CheckBox></ListBox>

If you do not use ListBoxItem to fill in the list items, when you read the SelectedItem value, you will not get the ListBoxItem object, but the object you placed in the list. In the preceding example, SelectedItem provides a CheckBox object.

The following code gets the selected item and shows whether the item is selected.

private void lst_SelectionChanged(object sender, SelectionChangedEventArgs e){    if (lst.SelectedItem == null) return;    txtSelection.Text = String.Format(      "You chose item at position {0}.\r\nChecked state is {1}.",      lst.SelectedIndex,      ((CheckBox)lst.SelectedItem).IsChecked);}

If you want to know which project has no choice, you can use the RemovedItems attribute of the SelectionChangedEventArgs object. Similarly, the AddedItems attribute tells you which project is added to the selection. In single-choice mode, a project is always added and removed whenever it is selected to change. In multiple or extended mode, it is not necessary.

The following code traverses the list project set:

private void cmd_ExamineAllItems(object sender, RoutedEventArgs e){    StringBuilder sb = new StringBuilder();    foreach (CheckBox item in lst.Items)    {        if (item.IsChecked == true)        {            sb.Append(item.Content);            sb.Append(" is checked.");            sb.Append("\r\n");        }    }    txtSelection.Text = sb.ToString();}

 

ListBoxItem also has some additional functions: IsSelected attributes, Selected events, and Unselected events. These functions can also be implemented through the SelectedItem attribute of ListBox and the SelectionChanged event.

Interestingly, there is a technology that gets the ListBoxItem package of the specified object when you use the nested object method. The trick is the ContainerFromElement () method. This is the code that uses this technology to check whether the first project is a list of selected items:

var item = (ListBoxItem)lst.ContainerFromElement(  (DependencyObject)lst.SelectedItems[0]);MessageBox.Show("IsSelected: " + item.IsSelected.ToString());
ComboBox

The usage of the combo box is basically the same as that of the list box.

If you allow users to select a project by typing text in the combox, you must set the IsEditable attribute to true and ensure that you store plain text-only ComboBoxItem objects, or an object that provides meaningful ToString () notation. For example, if you fill in an editable box with an Image object, the text appears in the above section as the full name of the Image class, which is not very useful.

Range-based controls

The range-based Control base class is the RangeBase class, derived from the Control class. Including ScrollBar, Slider, and ProgressBar. Attributes of the RangeBase class include:

Value, Maximum, Minimum, SmallChange, LargeChange

Because of the ScrollView control, ScrollBar is rarely used. Now follow the Slider and ProgressBar.

Slider

See page 188

ProgressBar

See page 190

Date Control

For details, see page 190.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.