当前位置:网站首页>Custom controls under WPF and adaption of controls in Grid
Custom controls under WPF and adaption of controls in Grid
2022-06-28 03:26:00 【Bright in snow】
「 Blog move 」 New address : Simple books
This article mainly summarizes the use of C# And .NET stay WPF Within the framework of , Customize the drawing of controls and the adaptation of controls in the form .
1. WPF Under the custom control
WPF Next , To quickly customize a component for an application , What is needed is UserControl , To make your controls more standardized , More flexible and universal , needed CustomControl . To be in WPF Customize a control in , Use UserControl And CustomControl All good choices , The difference between them is :
UserControl , More like WinForm The development style of custom controls in , It is simpler and faster in development , It can be almost simply understood as : Use the designer to piece together multiple existing controls as child elements to form a UserControl And modify its appearance , Then the background logic code directly accesses these sub elements . Its biggest drawback is : It has poor support for template styles , The scope of its reuse is limited .
CustomControl , The developed controls really have WPF style , It has good support for template styles , This is because of the creation of CustomControl The logical code is separated from the appearance , Even if you change to a completely different set of visual trees, it can also work well , It's like WPF Built in controls .
In the use of Visual Studio When building controls , UserControl And CustomControl The difference is even more obvious , Add a UserControl when , We will find that the designer has added a XAML File and a corresponding .CS file 「 or .VB etc. 」, Then you can design this as you would a normal form UserControl ; If we are adding a in the project CustomControl , This is not the case , The designer will generate a .CS file 「 or .VB etc. 」, This file is used to write the background logic of the control , The appearance of the control is defined in the application theme of the software 「Theme」 It's in 「 If you don't define common themes for Software , It will automatically generate a generic theme
themes\generic.xaml, Then the theme will automatically generate a Style 」, And associate the general theme with the control . This is the same. CustomControl Support for style ratio UserControl Good reason .
Here, for simplicity , Use UserControl Create custom controls .
1.1 newly build UserControl
Right click on the item , choice 「 add to 」->「 New item 」, choice 「 User control 『WPF』」”, You can successfully add a custom control .

Design the control , Drag in several system controls , And modify its parameters . The figure below shows that I use Microsoft Blend Design the control :

1.2 UserControl The basic code of
After the control is designed , Right click the control edit window , choice 「 Look at the code 」, Or press directly 「F7」 key , You can edit the source code of the control class . I mainly added the initialization of this control , Change the background color of the control , And code functions such as dynamically setting the value displayed by the control , As follows :
/// <summary>
/// _bitkyPoleControl.xaml Interaction logic of
/// </summary>
public partial class BitkyPoleControl : UserControl
{
private readonly Color _colorBlue = Color.FromRgb(0, 255, 200);
// Color change
private readonly Color _colorRed = Color.FromRgb(255, 0, 0);
public BitkyPoleControl()
{
InitializeComponent();
}
public int _id { get; private set; } = -1;
/// <summary>
/// Initialize the control according to the parameters
/// </summary>
/// <param name="id"> Input parameters </param>
public void setContent(int id)
{
Name = "bitkyPoleControl" + id;
labelPoleId.Content = id;
_id = id;
}
public void SetValue(int num)
{
labelNum.Content = num;
}
/// <summary>
/// Set the background color ,0: green 1: red
/// </summary>
/// <param name="i"></param>
public void setColor(int i)
{
if (i == 0)
Background = new SolidColorBrush(_colorBlue);
if (i == 1)
Background = new SolidColorBrush(_colorRed);
}
}2. Grid Dynamic addition of controls in
2.1 In the main form Grid Configuration of
I added a... In the main form Grid , And put the Grid It is divided into eight rows and eight columns , As shown in the figure below :

The setting method is as follows : As shown in the figure below , Through to Grid The properties of the are set as follows :
- stay 「1」 It's about , Additable ColumnDefinitions and RowDefinitions .
stay 「2」 It's about , Can be set up Grid The minimum size of the cell in the , stay width It's about , There are three options :「Auto」,「Pixel」,「Star」.
- ”Auto”: The system automatically sets the size according to the situation .
- “Pixel”: Set to absolute size , Not adaptive .
- “Star”: Set the specific gravity , Each row or column is allocated according to the set proportion Grid Space .
Here it is , To distribute evenly Grid Space , And it can be adaptive according to the window size , Therefore, this item of all rows and columns is set to 「Star」, Value to 「1」, The effect of the above figure will appear .

2.2 Grid Add controls dynamically in
Use the following code in the main form class to Grid Add controls dynamically in :
/// <summary>
/// Initialize the information display tab interface
/// </summary>
private void InitBitkyPoleShow()
{
var controls = new List<BitkyPoleControl>();
var id = 0;
for (var i = 0; i < 8; i++)
{
for (var j = 0; j < 8; j++)
{
var bitkyPoleControl = new BitkyPoleControl();
// stay Grid Add controls dynamically in
GridPoleStatusShow.Children.Add(bitkyPoleControl);
// Set control in Grid Position in
Grid.SetRow(bitkyPoleControl, i);
Grid.SetColumn(bitkyPoleControl, j);
// Add control to collection , Convenient for the next step
controls.Add(bitkyPoleControl);
// Use custom methods to initialize the control
bitkyPoleControl.setContent(id);
id++;
}
}
}Run the program , The effect is shown below :

Look at the pictures , The space layout is more beautiful , If you want the child controls to be fully populated Grid Cells in , You need to configure the properties of child controls .
3. Grid Dynamic adaptation of child controls
3.1 Configure the properties of child controls

As shown in the figure , Set the width and height of the control to 「Auto」, take HorizontalAlignment and VerticalAlignment Set to 「Stretch」 , Margin Set to the appropriate value , Now , Grid Can dynamically adapt the parent control .

4. Reference material
边栏推荐
- crond BAD FILE MODE /etc/cron. d
- TypeError:&nbsp;&#039;module&amp;#03…
- 导致系统性能失败的十个原因
- 数据库乱码问题
- apache、iis6、ii7独立ip主机屏蔽限制ip访问
- 導入Excel文件,解决跳過空白單元格不讀取,並且下標前移的問題,以及RETURN_BLANK_AS_NULL報紅
- nn. Parameter and torch nn. Init series of functions to initialize model parameters
- Reading makes people quiet
- Packet capturing and sorting out external Fiddler -- understanding the toolbar [1]
- collections. Use of defaultdict()
猜你喜欢

2022年R1快开门式压力容器操作特种作业证考试题库及答案

剑指 Offer 49. 丑数(三指针法)

2022年R1快開門式壓力容器操作特種作業證考試題庫及答案

How to write concise code? (upper)

【PaddleDetection】ModuleNotFoundError: No module named ‘paddle‘

View the SQL execution plan according to explain and optimize the SQL

在excel文件上设置下拉选项

建立自己的网站(17)

Dataloader参数collate_fn的使用

如何获取GC(垃圾回收器)的STW(暂停)时间?
随机推荐
没错,是水的一篇
如何给Eclips自动添加作者,时间等…
华为设备WLAN基本业务配置命令
嵌入式DSP音频开发
Is it safe to buy stocks and open an account through the account opening link of the broker manager? Want to open an account for stock trading
Idea auto generate code
Dataloader parameter collate_ Use of FN
Build your own website (17)
Agileplm exception resolution session
Apache——阿帕奇简介
composition api在项目中的使用总结
crond BAD FILE MODE /etc/cron.d
读书,使人内心宁静
同样是MB,差距怎么这么大呢?
R language penalty logistic regression, linear discriminant analysis LDA, generalized additive model GAM, multiple adaptive regression splines Mars, KNN, quadratic discriminant analysis QDA, decision
Etcd database source code analysis -- network layer server rafthandler between clusters
Is online stock investment exchange group safe? Is it reliable to open an account for free?
剑指 Offer 47. 礼物的最大价值(DP)
matlab习题 —— 数据的基本处理
Thesis reading: General advantageous transformers