当前位置:网站首页>C basic knowledge review (Part 3 of 4)
C basic knowledge review (Part 3 of 4)
2022-07-05 01:12:00 【ErrorError!】
The first 6 Chapter Directory and file operations
Catalog
- The first 6 Chapter Directory and file operations
- The first 7 Chapter WPF Getting started with Applications
- The first 8 Chapter WPF Control
6.1 Directory and file management
6.1.1 Environment Classes and DriveInfo class
Environment class : Use Environment Class can retrieve information related to the operating system
Common static properties :
1.CurrentDirectory attribute : Get the folder where the assembly is located ;2.OSVersion attribute : Get the operating system version (PC,PDA support );3.NewLine attribute : Get the current environment newline (PC Support );4.Version attribute : Object that displays the common language runtime version ;5.GetLogicalDrives Method : List local hard drives (PC Support );6.GetFolderPath Method : Get the system reserved folder path (PC,PDA support )
DriveInfo class : Use DriveInfo You can determine the currently available drives and the types of these drives , You can also query to determine the capacity and remaining space of the drive
DriveInfo[] allDrives = DriveInfo.GetDrives( );
foreach (DriveInfo d in allDrives)
{
Console.WriteLine("Drive {0}", d.Name);
Console.WriteLine(" file type : {0}", d.DriveType);
if (d.IsReady == true)
{
Console.WriteLine(" Volume label : {0}", d.VolumeLabel);
Console.WriteLine(" file system : {0}", d.DriveFormat);
Console.WriteLine(" Current user free space :{0} bytes", d.AvailableFreeSpace);
Console.WriteLine(" Total free space :{0} bytes", d.TotalFreeSpace);
Console.WriteLine(" Total drive capacity :{0} bytes ", d.TotalSize);
}
}
6.1.2 Path class
Path Class is used for String example Perform the operation , Common methods :
1.GetDirectoryName Method : Get the folder path of the file ;2.GetExtension Method : Get the file extension from the file path string ;3.GetFileName Method : Get the file name from the path string ( With extension );4.GetFileNameWithoutExtension Method : Get the file name from the path string ( Without extension );5.GetFullPath Method : Get the full pathname including the file name and extension from the file string ;
6.1.3 Directory management
Directory Classes and DirectoryInfo Class can be used to manage disks and directories , Like copying 、 Move 、 rename 、 establish 、 Delete directories, etc
The difference between the two classes is DirectoryInfo Class provides More detailed functions , And it must be instantiated before it can be used , and Directory Class only provides commonly used Static methods
Directory Static methods provided by class :
1.CreateDirectory: Create all directories in the specified path ;2.Delete: Delete the specified directory ;3.Move: Move the file or directory and its contents to a new location ;4.Exists: Determine whether the directory exists ;5.GetCurrentDirectory: Get the current working directory of the application
6.1.4 file management
System.IO File operation class in namespace :(1)File class ;(2)FileInfo class
The same thing : Can complete the copy of the file 、 Move 、 rename 、 establish 、 open 、 Delete and append to file operation
Difference :FileInfo Class provides instantiated properties 、 Method ,File Only static methods are provided
Usage and Directory and DirectoryInfo be similar
Copy file : File.Copy(path1, path2, true);,true Indicates if the target file already exists , Just cover it directly
Get or set file properties :
File Class provides SetAttributes Methods and GetAttributes Method . Used to get or set various attributes of the file . The prototype of the method is :
public static void SetAttributes(string path, FileAttributes fileAttributes)
public static FileAttributes GetAttributes(string path)
stay SetAttributes In the method , Use FileAttributes Enumeration to get or set the properties of a directory or file , Bitwise operation can be used in the program “&”、“|” Set or get a single attribute
“&: Bitwise AND ;”|": Press bit or ;
Determine whether a path is a directory or a file
if ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory){
Console.WriteLine("{0} Is a directory ", path);}
else{
Console.WriteLine("{0} It's a document ", path);}
6.2 Reading and writing of documents
stay System.IO In the namespace , It provides many kinds of read and write operations for data files and data streams :
1. File encoding , Provide a variety of codes ;2. Reading and writing text files ;3. Reading and writing of binary files
6.2.1 File encoding
Common file encoding methods :ASCII、Unicode、UTF8、ANSI、GB2312、GB18030
System.TextEncoding class : Express Character encoding , Commonly used
Encoding.Default Indicates the current of the operating system ANSI code
Encoding.Unicode Unicode code
Encoding.UTF8 UTF8 code
Be careful : open The encoding format specified in the document must be the same as preservation The coding format used in the document is consistent , Otherwise, what you see may be a pile of garbled code
6.2.2 Reading and writing text files
ReadAllText Methods and AppendAllText Method :
string path = @“E:\ls\MyTest.txt";
if (File.Exists(path))
{
File.Delete(path);
}
string appendText = " Hello ." + Environment.NewLine;
File.AppendAllText(path, appendText,Encoding.Default);
string readText = File.ReadAllText(path,Encoding.Default);
Console.WriteLine(readText);
ReadAllLines Methods and WriteAllLines Method
string path = @"c:\temp\MyTest.txt";
if (File.Exists(path))
{
File.Delete(path);
}
string[] appendText ={ " Company "," full name "," achievement "};
File.WriteAllLines(path, appendText,Encoding.Default);
string[] readText = File.ReadAllLines(path,Encoding.Default);
Console.WriteLine(string.Join(Environment.NewLine, readText));
6.2.3 StreamReader Classes and StreamWriter class
Stream is an abstract concept of byte sequence : Provides continuous Byte stream storage space , It is also the basic object for data reading
Flow has the following operations :
- Read : Read data from the stream into variables
- write in : Write the data in the variable to the stream
- location : Reset the current position of the stream , For random reading and writing
Be careful :StreamReader、StreamWriter The default encoding for is UTF-8
StreamReader class :
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine( )) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
StreamWriter class :
try
{
using (StreamWriter sw = new StreamWriter("TestFile.txt"))
{
sw.WriteLine("First line");
sw.WriteLine("The date is: {0}", DateTime.Now);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be write:");
Console.WriteLine(e.Message);
}
6.2.4 Reading and writing of binary files
System.IO.BinaryReader and BinaryWriter class : Read and write files in binary mode
- BinaryReader:ReadByte、ReadBoolean、ReadInt、ReadInt16、ReadDouble and ReadString etc.
- BinaryWriter: Provided with BinaryReader Corresponding to a variety of overloaded Write Method
The first 7 Chapter WPF Getting started with Applications
7.1 WPF Applications and XAML Mark
WPF:WPF It's a kind of “ Take attributes as the core ” Programming model . Mainly used for development C/S Client program ( such as QQ、360 Safety guard 、 Fetion 、 Stock software 、…… etc. ),WPF be based on DirectX and GPU Accelerated Graphical interface display technology ,WinForm The interface of is all used C# Code implementation ,WPF In addition to using C# To achieve beyond , You can also use XAML To achieve
APP class :App The base class of class is Application class , This class mainly defines resources and attributes that can be used throughout the application
The start of the program : The program from Main Method starts , But the method is hidden , Instead, let developers pass App.xaml File to set up
<Application x:Class="Source.App" …… StartupUri="MainWindow.xaml">
<Application.Resources>
……
</Application.Resources>
</Application>
App Common properties of class 、 Methods and events :
StartupUri attribute : stay App.xaml Set in ;
MainWindow attribute : When App Of Shutdown The model is MainWindow Only when App.xaml.cs Set this property in the constructor of ( Specify who is the main window ):
public partial class App : Application
{
public App() { // Set... Here ...... }
}
Other attributes : In any window or page, you can get or set
WPF Application shutdown mode :
- Can be in App.xaml Pass through ShutdownMode Specify the shutdown mode :
<Application x:Class="Source.App" ……ShutdownMode="OnMainWindowClose" StartupUri="MainWindow.xaml">
ShutdownMode Value of property :1.OnLastWindowClose( Default ): Automatically close the application when closing the last window ;2.OnMainWindowClose: Automatically close the application when closing the main window ;3.OnExplicitShutdown: Only if you explicitly call Shutdown When the method is used , Just close the application ;
- No matter which shutdown mode , Just call App.Current.Shutdown() Method , Will immediately close the application
XMAL Namespace and x: Prefix programming constructs : Statement XAML Namespace solves XAML Labelling and C# The problem of code sharing
- The root element and XAML Namespace
- One XAML file ( extension .xaml The file of ) There can only be one root element
- x:Class Is used to XAML Associated with code behind classes
- xmlns Feature declaration XAML Default namespace
- x: Prefix programming constructs
- Root element xmlns:x be used for XAML Namespace mapping , The purpose is to pass x: Prefix declarations can be used by others XAML and C# The object referenced by the code
- The control of Name characteristic : The purpose of the declaration is to reference it in the code behind class
- Only in the template 、 Custom control 、 Only for special occasions such as animation x:Name characteristic
- stay XAML Mapping custom namespaces in
- stay XAML I quote Custom object , Must be in XAML in Map custom namespaces
Add : stay XAML Custom namespace in
<Page x:Class="Source.ch07.Page1" …… xmlns:my="clr-namespace:Source.ch07" …… Title="ch07Page1">
<StackPanel>
……
<my:UserControl1 x:Name="uc1" />
</StackPanel>
</Page>
// If you will x:Name Change it to Name, You won't see it in code behind classes uc1
//StackPanel: The longitudinal ( Default ) Or horizontal stacking layout
XAML Basic grammar
Concept :XAML Grammar and HTML The grammar of is very similar , That is, they all use elements 、 characteristic (Attribute) And attribute (Property) To describe the various elements of an element object ,XAML Object name in 、 Feature names and attribute names are case sensitive
(1) Object element syntax
An object is an instance of a class , stay XAML Object elements are used to describe . for example :
(2) Attribute syntax ( The most commonly used )
Use characteristics (Attribute) To describe the properties of an object (Property), An assignment number is used between the property name and the property value (=) Separate , The value of a property is always specified as a string , Quotation marks are double quotation marks by default , It can also be a single quotation mark , The principle is “ value ” The quotation marks on both sides must match . for example :
Feature syntax can also be used to describe event members . for example :
Click Me!
(3) Attribute Syntax : Sometimes it is impossible to describe some attributes of an object only by using feature syntax , At this time, attribute syntax can be used to describe . The general format is :
< Class name . Property name >……</ Class name . Property name >
for example :
<Button Background="Blue" Foreground="Red" Content=" Right click to observe the shortcut menu " Margin="73,108,74,115">
<Button.ContextMenu>
<ContextMenu>
<MenuItem> Shortcut menu items 1</MenuItem>
<MenuItem> Shortcut menu items 2</MenuItem>
</ContextMenu>
</Button.ContextMenu>
</Button>
(4) Set Syntax : If a property is of collection type , You can use set syntax . for example ( This code is using 【 attribute 】 Automatically generated after the window is set ):
<Window.Background>
<LinearGradientBrush>
<LinearGradientBrush.GradientStops>
<GradientStop Offset="0.0" Color="Red" />
<GradientStop Offset="1.0" Color="Blue" />
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Window.Background>
(5)XAML Content properties : The purpose of content attributes is to simplify markup , Or for nested sub elements . for example :
This is a Text Box
amount to :
(6) Combination of content attributes and set syntax
<StackPanel>
<Button> Button 1</Button>
<Button> Button 2</Button>
</StackPanel>
(7) Type converter
Convert property values set with strings to other object types or primitive values . for example :
<Button Margin="10,20,30,40" Content=" determine "/>
// amount to :
<Button Content=" determine ">
<Button.Margin>
<Thickness Left="10" Top="20" Right="30" Bottom="40"/>
</Button.Margin>
</Button>
XAML Blank handling in
XAML White space characters in include spaces 、 A newline 、 Box drawings, etc , By default ,XAML The processor will automatically convert all white space characters into spaces
Be careful : By default , Consecutive spaces will be replaced by “ One ” Space
If you want to keep multiple spaces in the text string , You can add xml:space=“preserve” characteristic , But be careful to avoid Root level Specify this property , Otherwise it will affect XAML Processing performance
7.2 Windows and dialog boxes
7.2.1 WPF window
Window classification :WPF The window is composed of non working area and working area , The non working area mainly includes icons 、 title 、 system menu 、 Buttons and borders
adopt 【WindowStyle】 Property to set the window style :
1. Standard Windows (SingleBorderWindow, Default );
2. Untitled window (None): Only the work area ;
3. Tool window (ToolWindow): There is only a close button in the upper right corner of the non working area , Exclude minimization 、 Maximize and restore buttons ;
4. Notification icon (NotifyIcon);
Window life cycle :( A series of processes from opening the window for the first time to closing it )
Activate window
Active window : Currently capturing user input ( Such as keyboard or mouse ) The window of
When opening a window for the first time , This window becomes the active window . When the window becomes active , May trigger Activated event --> Raised when the currently active window is deactivated Deactivated event --> utilize IsActive Property to check whether the window is active
Create and display a new window : stay C# Call in code Show Method ( Modeless window ) perhaps ShowDialog Method ( modal window ) Display window , about “ Modeless ” window , call Hide Method can hide it
close window : Call directly Close Method to close the currently open window , Two events will be raised when the window is closed :Closing Events and Closed event
Window Association : By setting the Owner Property to attach the child window to its parent window
Window ownedWindow = new Window();
ownedWindow.Owner = this;
ownedWindow.Show();
7.2.2 The appearance and behavior of the window
appearance : Refers to the window representation seen by the user , Behavior : Refers to the way users interact with windows
Window size : The window size is determined by Width、MinWidth、MaxWidth、Height、MinHeight、MaxHeight as well as SizeToContent Wait for multiple attributes to be determined , Detect the current width and height of the window : Should check ActualWidth and ActualHeight attribute
window position : adopt Left and Top Property to get or change the relative coordinates of the window to the screen x and y Location ,WindowStartupLocation attribute Set the initial position of the window when it is first displayed , Enumeration values are :Manual( Default )、CenterScreen、CenterOwner
z Order and topmost window : At the top z Windows in order are always in normal z Above the window in the order , The of the window Topmost Property is set to true You can make this window at the top z In sequence
7.2.3 Dialog box
Message box ( MessageBox class )
Call static Show Method to display a message box , Common overloads are :
- public static DialogResult Show(string text)
- public static DialogResult Show(string text, string caption)
- public static DialogResult Show(string text, string caption, MessageBoxButton buttons,MessageBoxImage icon)
Reference link :
Common dialog box :
Reference link :
C# The use of General dialog boxes in interface design
Custom dialog : Custom dialog boxes are generally used to display and collect specific information , Divided into Mode dialog ( call ShowDialog Method display ) And modeless dialogs ( call Show Method display )
7.2.4 WPF Page and page navigation
The main points of :(1) stay WPF In the application , You can use windows (Window) Design interface , You can also use pages (Page) Design interface ;(2) use Page when , It can be done by Frame perhaps NavigationWindow To carry
stay Frame Medium load Page( Commonly used ): stay Frame Element Source Property is set to the page to navigate to , In this way , You can use XAML Load the page and navigate , It can also be used. C# Code to implement
// use XAML Realization
<Frame Name="frame1" NavigationUIVisibility="Visible" Source="Page1.xaml" Background="#FFF9F4D4" />
// use C# Realization
frame1.Source = new Uri("Page1.xaml", UriKind.Relative);
7.3 Color
Any color is red (R)、 green (G)、 blue (B) The changes of the three color channels and the superposition between them
adopt Alpha Channel can control the transparency of color
Common color formats :#aarrggbb
<StackPanel>
<StackPanel.Resources>
<Style TargetType="Label"> <Setter Property="Margin" Value="0 5" /> <Setter Property="Content" Value="Hello" /> <Setter Property="Foreground" Value="White" /> </Style>
</StackPanel.Resources>
<Label Background="#FF5E7C4C" />
<Label Background="#FF1A36E6" />
<Label Background="#FFE63F1A" />
</StackPanel>
Brushes Classes and Colors class :
stay System.Windows.dll Medium System.Windows.Media Under the namespace Brushes Classes and Colors Classes use static attributes to provide predefined colors , These colors can be used in various applications . Such as setting the foreground color of the control 、 Background color 、 Border color, etc
Brushes Class C# grammar ( Hidden class ,sealed Indicates that the class cannot be inherited ):public sealed class Brushes
Colors Class C# grammar :public sealed class Colors
These two classes can only get or set colors through the static properties they provide
Color structure :
The structure passes through A( transparency )、R( the red channel )、G( Green channel ) and B( Blue channel ) To create a variety of custom colors , The general form is :“#rrggbb” perhaps “#aarrggbb”
among # For hexadecimal ,aa Presentation transparency ,rr Indicates the red channel ,gg Indicates green channel ,bb Indicates blue channel
7.4 shape
The main points of :(1) The base class of shapes is Shape class , Other categories (Ellipse、Line、Path、Polygon、Polyline and Rectangle) Are extensions of this class ;(2)Canvas Panels are particularly ideal for creating complex drawings , Because it supports absolute positioning of its children
Properties common to shape controls :
- Stroke: Draw shape outline
- StrokeThickness: Specify the thickness of the shape outline
- Fill: Fill the inside of the shape
- Stretch:None( No stretching )、 Fill( The tensile 、 The aspect ratio is not preserved );Uniform( Stretch as much as possible , And retain its original aspect ratio );UniformToFill( Full stretch , And retain its original aspect ratio )
rectangular :Rectangle Class is used to draw rectangles
<Canvas>
<Rectangle Width="100" Height="100" Fill="Blue" Stroke="Red" Canvas.Top="20" Canvas.Left="20" StrokeThickness="3" />
</Canvas>
The ellipse :Ellipse Class is used to draw ellipses , When Width and Height When equal , What you draw is actually a circle
<Canvas Background="LightGray">
<Ellipse Height="75" Width="75" Fill="#FFFFFF00" StrokeThickness="5" Stroke="#FF0000FF"/>
</Canvas>
Other basic shapes :
- Line( A straight line )
<Line X1="10" Y1="10" X2="50" Y2="50" Stroke="Black" StrokeThickness="4" />
- PolyLine( Multiple straight lines connected in turn )
<Canvas>
<Polyline Points="50,25 0,100 100,100 50,25" Stroke="Blue" StrokeThickness="10" Canvas.Left="75" Canvas.Top="50" />
</Canvas>
- Polygon( polygon ) The control and PolyLine Similar usage , But it will automatically put the last 1 Point and number 1 Connect the dots
<Canvas>
<Polygon Points="300,200 400,125 400,275" Stroke="Purple" StrokeThickness="2">
<Polygon.Fill>
<SolidColorBrush Color="Blue" Opacity="0.4"/>
</Polygon.Fill>
</Polygon>
</Canvas>
7.5 paint brush
stay WPF In the application , paint brush (Brush) It is the basic function of all controls . The most common is to use the brush to set the foreground color of the control 、 Background color , Fill in gradients 、 Images and patterns
7.5.1 Brush classification
(1) All types of brushes are in System.Windows.Media Under the namespace
(2)Brush Classes are all kinds of brushes Abstract base class , Other brush types are inherited from this class
(3) Common brush types :
- Solid brush : Single color
- Gradient brush : Including linear gradients 、 Radial Gradient
- Image brush : You can use an image as a brush
(4) stay XAML Or select a control in the document outline , Direct utilization 【 attribute 】 Window setting brush type
7.5.2 Solid brush (SolidColorBrush)
establish SolidColorBrush After the instance , It can be done by Color Class to set the color
SolidColorBrush b = new SolidColorBrush();
b.Color = Color.FromArgb(0xFF, 0xFF, 0x0, 0x0);
button1.Background = b;
7.5.3 Linear gradient brush (LinearGradientBrush)
(1) meaning : Along a straight line ( Gradient axis ) Defined gradient drawing area
(2) use StartPoint and EndPoint Set the start and end points of the gradient , use GradientStop Set the color of the gradient stop 、 Offset
(3) If you do not specify the gradient direction , Create diagonal gradient by default .
<StackPanel>
<Rectangle Width="200" Height="100">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="Yellow" Offset="0.0" />
<GradientStop Color="Red" Offset="0.25" />
<GradientStop Color="Blue" Offset="0.75" />
<GradientStop Color="LimeGreen" Offset="1.0" />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
</StackPanel>
7.5.4 Radial gradient brush (RadialGradientBrush)
(1) meaning : Take an ellipse as the boundary , Gradually fill the gradient color from the center of the ellipse from the inside out
(2) The brush starts from the origin (GradientOrigin)、 Center point (Center) And the range of radiation (RadiusX、RadiusY) To define
<StackPanel>
<Rectangle Width="200" Height="100">
<Rectangle.Fill>
<RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5 " RadiusX="0.5" RadiusY="0.5">
<GradientStop Color="Yellow" Offset="0" />
<GradientStop Color="Red" Offset="0.25" />
<GradientStop Color="Blue" Offset="0.75" />
<GradientStop Color="LimeGreen" Offset="1" />
</RadialGradientBrush>
</Rectangle.Fill >
</Rectangle>
</StackPanel>
7.5.5 Graphic brush (ImageBrush)
(1) meaning : Use ImageSource Draw an area .
(2)XAML Example
<Rectangle Width="75" Height="75">
<Rectangle.Fill>
<ImageBrush ImageSource=“images/p1.jpg" />
</Rectangle.Fill>
</Rectangle>
(3)C# Example
Rectangle r = new Rectangle{Width = 75, Height = 75};
ImageBrush b = new ImageBrush();
b.ImageSource = new BitmapImage(new Uri(@“images\p1.jpg", UriKind.Relative));
r.Fill = b;
7.6 attribute
CLR attribute : use get and set The property implemented by the accessor is called CLR attribute
Dependency properties ( DependencyProperty ):
- encapsulation CLR attribute , The purpose is to use XAML Describe these properties
- Mainly used for style 、 The theme 、 Data binding 、 Animation 、 Metadata rewriting 、 Attribute value inheritance and WPF Designer integration
- Every CLR Attributes have their corresponding dependency attributes , vice versa
Additional attributes : Specify the attributes of its parent element on a child element , Used to set the layout of child elements relative to parent elements ( Such as docking mode )
Use style resources to control the properties of the control :
(1) classification : Inline 、 The embedded ( Use framework element style and application style to realize ) And externally linked ( Use resource dictionary to realize )
(2) If some controls have the same properties , Use Style After setting the style of these attributes separately , These controls will automatically apply these styles
7.7 event
** stay XAML Registered events in **: stay XAML in , The general form of a declaration event is Event name =“ Event handler name ”
perhaps : Child element type name . Event name =“ Event handler name ”
Generally, events are attached through the event list
<Button Name="Btn1" Click="Btn1_Click"/>
stay C# Register events in the code : utilize += Registration events , utilize -= Cancellation of registration
public MainWindow(){
InitializeComponent();
Button1.MouseDoubleClick += Button1_MouseDoubleClick;}
void Button1_MouseDoubleClick(object sender, MouseButtonEventArgs e){
// Event handling code }
Parameters in the event handler : all WPF Event handlers provide two parameters by default
private void OkButton_Click(object sender, RoutedEventArgs e)
Parameters sender Include The object to which this event is attached , Parameters e yes Relevant data of data source
Key points of event use :
(1) stay WPF in , most In all cases, use e.Source To determine the source of the event
(2) Most of the time through 【 attribute 】 The window directly sets the event of an element
(3) If there are many elements of the same type , And these elements will cause the same event , At this time, it can be in its parent element Declare additional events ( The number of event declarations can be simplified )
Event routing : direct 、 Bubbling and tunneling
1) Direct routing : direct (Direct) It means that the event is only for the element itself , Instead of routing to other elements
2) Bubbling : Bubbling (Bubble) It refers to finding the parent element from the event source in turn , Until the root element is found , The purpose is to search whether the parent element contains an attachment event declaration for that element
utilize “ Bubbling ” You can register the same event for multiple child elements at one time on a parent element :
<StackPanel …… Button.Click="Button_Click" ……>
<Button Name="YesButton" Content=" yes " Width="54" />
<Button Name="NoButton" Content=" no " Width="65"/>
<Button Name="CancelButton" Content=" Cancel " Width="64"/>
</StackPanel>
3) Tunnel routing : Tunnel (Tunnel) It refers to routing from the root element to the child elements in turn , Until the event source is found , It is just the opposite process of bubble routing
<Window ……>
<Border ……>
<StackPanel …… Button.PreviewMouseMove="Button_PreviewMouseMove" ……>
<Button Name="YesButton" Content=" yes " Width="54" />
<Button Name="NoButton" Content=" no " Width="65"/>
<Button Name="CancelButton" Content=" Cancel " Width="64"/>
</StackPanel>
</Border>
</Window>
Mouse events :
RoutedEventArgs Of Source Properties and OriginalSource attribute :
RoutedEventArgs Of Source attribute : Determine which element caused the event
OriginalSource attribute : It is generally used to judge which sub item in the element caused the event
1) Get the mouse position :GetPosition(IInputElement) Method : Get the position of the mouse cursor relative to the upper left corner of the specified control
Parameter value :
- null or this: be relative to Root element Coordinates of the content area
- sender: Based on targeting The object that handles the event Calculate the internal coordinates of
- Specifies the element object : Relative to the upper left corner of the specified object
2) Save and restore control state : Each control has a Object Type of Tag attribute , Use this property , You can save and restore multiple states before and after the control changes .
3) Set the cursor shape of the mouse :Mouse There is one in the class OverrideCursor attribute , Using this attribute, the shape of the cursor can be dynamically changed
Mouse.OverrideCursor = Cursors.Hand;
Keyboard events : To make a control accept keyboard events , The control's Focusable Property is set to true
The event name passed | Function description |
---|---|
KeyDown | When the keyboard is pressed |
KeyUp | When the keyboard is released |
GotKeyboardFocus | When the element gets input focus |
LostKeyboardFocus | Occurs when an element loses input focus |
Touchpad events :
stay WPF In the application , It can receive input from multiple touch at the same time , And when touch occurs ( Double click with your index finger 、 Move by hand 、 Enlarge the thumb and forefinger separately 、 Thumb and index finger close together, shrink, etc ) Cause corresponding events
The first 8 Chapter WPF Control
8.1 Control model and content model
WPF Control two basic models : Control model 、 Content model
8.1.1 WPF Control model
Components :
Content : Refers to the area where the content of the control is displayed , It can be text 、 Image or other control elements
Padding: padding . That is, the rectangular ring area between the border and the content
Frame : That is, the black rectangular ring area between the inner margin and the outer margin
Margin: Margin . Refers to the rectangular ring area surrounded by the border and the dotted line in the figure , Represents the distance between this control and other controls , There are usually two forms , One is to use a value to describe , The other is according to “ Left 、 On 、 Right 、 Next ” In the order of 4 Values describe . For example, the following code represents Button2 The left of the button 、 On 、 Right 、 The outer margins under are 0、10、0、10
padding (Padding): Controls the spacing between elements and their child elements or text , Its usage and Margin The usage of attributes is similar
Alignment mode :
- Horizontal alignment (HorizontalAlignment) : Declaring element Relative to its parent element Horizontal alignment of
become member | say bright |
---|---|
Left、Center、Right | The child element is aligned at the left end of its parent element 、 Center alignment 、 Align the right end |
Stretch( Default ) | Stretch the allocated space of the child element to the parent element . If declared Width and Height, be Width and Height first |
- The vertical alignment (VerticalAlignment): Describes the vertical alignment of an element relative to its parent element . The possible values are Top( Top alignment )、Center( Center alignment )、Bottom( Bottom alignment ) and Stretch( Default , Vertical stretch )
8.1.2 WPF Content model
WPF Content model refers to how to organize and layout WPF The content of the control . use XAML When describing control elements , The general grammatical form is :
< Control element name >
Content model
</ Control element name >
1. Text and Inlines:
Text The content model represents a string .TextBox、PasswordBox All belong to Text Content model
Xaml: This is a text
C#: textBox1.Text=“ This is a text ”;
Inlines The content model also represents a string of text , and Text Is the difference between the Inlines You can set the font name for each substring 、 bold 、 Italics and other styles
<TextBlock Name="textBlock1" TextWrapping="Wrap">
utilize <Bold> This control </Bold> Sure <Italic> Quick display </Italic> A small amount of text
</TextBlock>
2. Content:
Content The content model represents that the content is an object , The object can It's the text 、 Images and other elements . image Button、RepeatButton、CheckBox、RadioButton And Image All belong to this model
3. HeaderedContent:
HeaderedContent Indicates that its content model is 1 A title and 1 Content items , Both are arbitrary objects .
TabItem Is a special type of content control , Use it to set content and title
4. Items:
Items Represents a collection of items . You can set the of the control Items Property to directly populate each item of the control
WPF How to create control objects in an application
stay WPF In the application , There are two ways to create control objects
(1) static state ( Fixed ) Elements are generally used XAML To achieve .
(2) Dynamically changing elements ( Adding and deleting elements are determined by other factors ) It's usually used C# Code to implement
8.2 Common layout controls
8.2.1 WPF Layout classification
The layout methods are : Absolute positioning ( Graphics generally adopt absolute positioning )、 Dynamic positioning
In development , except Canvas The sub elements of adopt absolute layout , Elements in other layout elements should adopt dynamic layout
- grid (Grid)
(1) It is the only control in all dynamic layout controls that can dynamically adjust the allocated space in proportion
(2)Grid Child elements within can also be nested Grid
Grid Child elements use the following additional attributes to locate :
- use Grid.Row、Grid.Column Specify the row and column where the child element is located , stay C# Use in code Grid.SetRow Methods and Grid.SetCol Method specification
- Grid.RowSpan Across multiple lines . for example Grid.RowSpan="2" Cross 2 That's ok
- Grid.ColumnSpan Across multiple columns . for example Grid.ColumnSpan ="2" Cross 2 Column
(3) Automatically adjust row height and column width (Auto、*)
- Stack panels (StackPanel)
Arrange or stack sub elements in vertical or horizontal order . When there is no overlap, it is called arrangement , When there is overlap, it is called stacking
Common properties :Orientation attribute , The direction of arrangement or stacking . The default is vertical , If you want to arrange or stack horizontally , Set this property to “Horizontal” that will do
- canvas (Canvas)
Canvas Used to define an area , Called canvas . All child elements in the canvas use coordinate positions relative to the upper left corner of the area x and y To locate , The advantage is the high efficiency of execution , The disadvantage is that its child elements cannot be dynamically positioned , Also cannot automatically resize
Absolute positioning layout should be used in the following cases :
1. When there is only one image or graphic sub element in the region , Absolute positioning layout should be used
2. When C# When the code needs to use the coordinate position of the child element in this area , Absolute positioning layout should be used
- Frame (Border)
Used to draw a border around an element , Or provide a background for an element
Common properties :
- CornerRadius: Gets or sets the fillet radius of the border
- BorderThickness: Gets or sets the thickness of the border
- Padding: Get or set Border The distance between the child objects it contains
- Docking panel (DockPanel)
Used to define an area , And make the sub elements in the region on it 、 Next 、 Left 、 The right edges are docked horizontally or vertically
Common properties :
- LastChildFill: The default is true, Indicates that the last child element always fills the remaining space . If this property is set to false, You must also explicitly specify the docking direction for the last child element
- ockPanel.Dock: The child element specifies how it is docked in the parent element
8.3 Common basic controls
1、 Button (Button、RepeatButton)
Button: In addition to displaying text, you can also display images or both images and text
RepeatButton: It will automatically trigger its... Repeatedly within the time period from pressing the button to releasing the button Click event
Delay attribute : Specify the start time of the event Interval attribute : Control the interval of repetition
2、 Text block (TextBlock) And labels (Label)
TextBlock: Display read-only text that can be formatted , Font series can be specified separately 、 style 、 Thickness or size
Label:Label The content model of is Content, Therefore, other objects can be included
Generally will Label And TextBox Use it together , Used to display descriptive information 、 Verify information or enter instructions
3、 The text box (TextBox、PasswordBox、RichTextBox)
TextBox:TextBox Control is used to display or edit plain text characters
Text: Represents the displayed text ;
MaxLength: Limit the number of characters entered by the user ;
AcceptsReturn: False( Default )、True( Press enter to wrap );
TextWrapping: Controls whether to automatically go to the next line , When its value is “Wrap” when , The control can automatically expand to accommodate multiple lines of text ;
BorderBrush: Border color ;
BorderThickness: Border width , If you do not want this control to display a border , Set it to 0 that will do
PasswordBox: Password input
PasswordChar attribute : Mask , That is, no matter what character you enter , All displayed are characters specified by it ;
Password attribute : Get or set the entered password string ;
PasswordChanged event : Occurs when the password string changes
Be careful : PasswordBox Should use the PasswordChanged event , Out-of-service
KeyDown、MouseDown perhaps MouseUp Events
4、 Radio button (RadioButton)
Choose one of several options , Its content model is ContentControl, That is, the object elements it contains can be of any type ( character string 、 Image or panel ), But it can only contain one object element
GroupName attribute : grouping . Multiple in the same group RadioButton This attribute should be set to the same value ;
IsChecked attribute : Whether to select a radio button , Selected as true, Otherwise false
5、 Check box (CheckBox)
Select multiple items or different states of one item at the same time . The content model is ContentControl
Content attribute : Displayed text ;
IsChecked attribute :true Indicated selection ,false Indicates that... Is not selected ,none Indicates uncertainty ;
IsThreeState attribute : If the support 3 States , Then for true; Otherwise false. The default value is false. If the property is true, Can be IsChecked Property is set to null As a first 3 States ;
Click event : Occurs when the check box is clicked . Use this event to determine which of the three states ;
Checked event : Occurs when the check box is selected ;
UnChecked event : Occurs when the check box is not selected
6、 List box (ListBox) And drop-down boxes (ComboBox)
ListBox: Used to display a set of options , The content model is Items, Each option can be either a string , It can also be an image
ComboBox: yes “TextBox+ Ejectable ListBox” The combination of , It's more than ListBox One more. TextBox outside , The operation of each option is the same as ListBox In the same way
Common properties :
Count attribute : Get the number of list items ;
SelectedIndex attribute : Get the currently selected item from 0 The starting index number , When no item is selected, the value is −1;
SelectedItem attribute : Get the currently selected item , When no item is selected, the value is null;
SelectionMode attribute : How to select list items
Common methods :
Items.Add Method : towards ListBox Add items to the list of items ;
Items.Clear Method : Remove all items from the collection ;
Items.Contains Method : Determines whether the specified item is in the collection ;
Items.Remove Method : Remove the specified object from the collection ;
SelectionChanged event : This event is raised when the selection changes
8.4 menu 、 Toolbar and status bar
1、 menu (Menu) And shortcut menus (ContextMenu)
(1)Menu
It can be displayed anywhere in the window , But it is usually displayed at the top of the window
(2)ContextMenu
Apart from Right click Outside the pop-up menu , Other usage and Menu Control is used in the same way
(3) The menu items of these two controls are through MenuItem To achieve
a)MenuItem You can also nest MenuItem, So as to realize multi-level menu
b) Set up MenuItem Of IsCheckable="true" Make it tick ( Default false)
c) It can be used InputGestureText Set shortcut key , You can also use Command Set system commands ( shear 、 Copy 、 Paste etc. )
2、 Toolbars (ToolBar、ToolBarTray) And status bar (StatusBar)
(1)ToolBar
It is usually displayed at the top of the window , By multiple Button、CheckBox、RadioButton、ComboBox And so on , Through these items, you can quickly execute some common commands provided by the program
(2)ToolBarTray
yes ToolBar The container of , Multiple... Can be placed in the container ToolBar, And you can drag and adjust with the mouse ToolBar The order of arrangement in the container
(3)StatusBar
Generally, it is displayed below the window , Display images and status information in horizontal arrangement
If the article helps you , Remember to support three times with one click ~~
边栏推荐
- BGP comprehensive experiment
- 创新引领方向 华为智慧生活全场景新品齐发
- 各大主流编程语言性能PK,结果出乎意料
- SAP ui5 application development tutorial 106 - how to improve the readability of SAP ui5 application routing URL trial version
- 微信小程序:全网独家小程序版本独立微信社群人脉
- Async/await you can use it, but do you know how to deal with errors?
- Apifox (postman + swagger + mock + JMeter), an artifact of full stack development and efficiency improvement
- Yyds dry goods inventory kubernetes management business configuration methods? (08)
- Global and Chinese markets for industrial X-ray testing equipment 2022-2028: Research Report on technology, participants, trends, market size and share
- 【纯音听力测试】基于MATLAB的纯音听力测试系统
猜你喜欢
【海浪建模1】海浪建模的理论分析和matlab仿真
7. Scala process control
What you learned in the eleventh week
Basic concept and usage of redis
How to use words to describe breaking change in Spartacus UI of SAP e-commerce cloud
Detailed explanation of multi-mode input event distribution mechanism
Redis(1)之Redis简介
Basic operations of database and table ----- create index
I was beaten by the interviewer because I didn't understand the sorting
Basic operation of database and table ----- phased test II
随机推荐
If the consumer Internet is compared to a "Lake", the industrial Internet is a vast "ocean"
每日刷题记录 (十三)
[wave modeling 2] three dimensional wave modeling and wave generator modeling matlab simulation
The performance of major mainstream programming languages is PK, and the results are unexpected
[Yocto RM]10 - Images
How to use words to describe breaking change in Spartacus UI of SAP e-commerce cloud
[wave modeling 3] three dimensional random real wave modeling and wave generator modeling matlab simulation
Analysis and comparison of leetcode weekly race + acwing weekly race (t4/t3)
Which financial products with stable income are good
整理混乱的头文件,我用include what you use
dotnet-exec 0.6.0 released
7. Scala process control
Global and Chinese market of portable CNC cutting machines 2022-2028: Research Report on technology, participants, trends, market size and share
Basic operation of database and table ----- phased test II
Armv8-a programming guide MMU (3)
小程序直播 + 电商,想做新零售电商就用它吧!
Basic operations of database and table ----- create index
[Yocto RM]10 - Images
Introduction to the gtid mode of MySQL master-slave replication
Heartless sword English translation of Xi Murong's youth without complaint