C# Winform 實現(xiàn)控件自適應(yīng)父容器大小的示例代碼
更新時間:2021年03月24日 10:39:44 作者:lcsyhh
這篇文章主要介紹了C# Winform 實現(xiàn)控件自適應(yīng)父容器大小的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧
在日常開發(fā)中經(jīng)常遇到控件不能隨著父容器大小的改變而且自動改變控件的所在位置和大小。以下是實現(xiàn)的代碼
/// <summary>
/// 根據(jù)父容器實現(xiàn)控件自適應(yīng)大小位置
/// </summary>
/// <param name="control">所需自適應(yīng)大小位置的控件</param>
private void ChangeLocationSizeByParent (Control control)
{
//記錄父容器大小,來判斷改變控件大小位置是因為父容器的改變還是通過設(shè)置控件大小位置去改變
Size parentOldSize = control.Parent.Size;
PointF locationPF = new PointF();
locationPF.X = (float)control.Location.X / (float)control.Parent.Width;
locationPF.Y = (float)control.Location.Y / (float)control.Parent.Height;
PointF sizePF = new PointF();
sizePF.X = (float)control.Width / (float)control.Parent.Width;
sizePF.Y = (float)control.Height / (float)control.Parent.Height;
control.LocationChanged += delegate (Object o, EventArgs e) {
if (control.Parent != null&&parentOldSize.Equals(control.Parent.Size))
{
locationPF.X = (float)control.Location.X / (float)control.Parent.Width;
locationPF.Y = (float)control.Location.Y / (float)control.Parent.Height;
}
};
control.SizeChanged += delegate (Object o, EventArgs e) {
if (control.Parent != null && parentOldSize.Equals(control.Parent.Size))
{
sizePF.X = (float)control.Width / (float)control.Parent.Width;
sizePF.Y = (float)control.Height / (float)control.Parent.Height;
}
};
control.ParentChanged += delegate (Object o, EventArgs e) {
if (control.Parent == null)
{
return;
}
locationPF.X = (float)control.Location.X / (float)control.Parent.Width;
locationPF.Y = (float)control.Location.Y / (float)control.Parent.Height;
sizePF.X = (float)control.Width / (float)control.Parent.Width;
sizePF.Y = (float)control.Height / (float)control.Parent.Height;
};
control.Parent.SizeChanged += delegate (Object po, EventArgs pe) {
Control pControl = (Control)po;
int x = (int)(pControl.Width * locationPF.X);
int y = (int)(pControl.Height * locationPF.Y);
control.Location = new Point(x, y);
int width = (int)(pControl.Width * sizePF.X);
int hetght = (int)(pControl.Height * sizePF.Y);
control.Size = new Size(width, hetght);
control.Refresh();
parentOldSize = pControl.Size;
};
}
到此這篇關(guān)于C# Winform 實現(xiàn)控件自適應(yīng)父容器大小的示例代碼的文章就介紹到這了,更多相關(guān)C# Winform 控件自適應(yīng)父容器大小內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#結(jié)合Minio實現(xiàn)文件上傳存儲與更新
MinIO是一個開源的對象存儲服務(wù)器,專門設(shè)計用于在大規(guī)模數(shù)據(jù)存儲環(huán)境中運行,這篇文章主要為大家介紹了C#如何結(jié)合Minio實現(xiàn)文件上傳存儲與更新,需要的可以參考下2024-03-03
C#中WPF ListView綁定數(shù)據(jù)的實例詳解
這篇文章主要介紹了C#中WPF ListView綁定數(shù)據(jù)的實例詳解的相關(guān)資料,希望通過本文能幫助到大家,讓大家理解掌握這部分內(nèi)容,需要的朋友可以參考下2017-10-10

