C#用户控件的一些尝试

    在设计完控件后,想要建立一个Windows窗体程序进行测试,但是一双击用户控件Visual 2013就停止运行,后面发现应该要先在Windows窗体项目应用中添加控件的引用,然后重新生成整个解决方案,问题就解决了。

    但接下来又产生了另一个问题,那就是控件在设计调用的时候显示不完全(我的控件里是组合了label和textbox两个控件的组合控件),我发现是我理解的方法调用含义不对,labelTest.Top代表的不是label顶端的位置,而是控件顶端与容器顶端的距离,所以当令labelTest.Top=0时,控件的上端就会与容器的上端对齐,以此解决了显示不全的问题。下面是整个控件的代码,实现了两个属性和设计时改变容器大小,内部复合控件进行重绘:

   

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;

namespace WindowsFormsControlLibrary1
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}

private void UserControl1_Load(object sender, EventArgs e)
{
labelTest.Text = Name; // 设置静态文本
textBoxTest.Left = labelTest.Right; // 静态文本右端对齐文本框左端
textBoxTest.Width = Width - labelTest.Right - 3; // 文本框宽度
}

public enum PositionEnum
{
Right,
Below
}
private PositionEnum Position = PositionEnum.Right;
private int TextBoxMargin = 0;

public PositionEnum getPosition
{
get { return Position; }
set
{
Position = value;
MoveControls();
}
}

public int getTextboxMargin
{
get { return TextBoxMargin; }
set
{
TextBoxMargin = value;
MoveControls();
}
}

private void MoveControls()
{
switch (Position)
{
case PositionEnum.Below:
labelTest.Top = 0;
labelTest.Left = 0;
textBoxTest.Top = labelTest.Bottom;
textBoxTest.Height=Height-labelTest.Bottom;
textBoxTest.Left = 0;
textBoxTest.Width = Width - labelTest.Right - 3;
//Height = textBoxTest.Height + labelTest.Height;
break;
case PositionEnum.Right:
labelTest.Left = 0;

if (TextBoxMargin == 0)
{
textBoxTest.Left = labelTest.Right; // 静态文本右端对齐文本框左端
textBoxTest.Width = Width - labelTest.Right - 3; // 文本框宽度
}
else
{
textBoxTest.Left = labelTest.Right+TextBoxMargin; // 静态文本右端对齐文本框左端
textBoxTest.Width = Width - labelTest.Right - 3; // 文本框宽度
}
//textBoxTest.Height = Height;
break;
}
}

private void UserControl1_SizeChanged(object sender, EventArgs e)
{
MoveControls();
}

}
}

显示的结果是:

拉伸后变成这样:

最后还是没有符合自己的预期,我想的是在设计时拉伸容器可以让内部的控件高和宽都进行等比例转换,可是总不能成功,中间借鉴了网上一些人的想法,改变控件的Anchor和Dock属性,但效果不好(估计自己没用对),只能让控件钉住随区域移动,但大小还是没变化,期待后续解决。。。

原文地址:https://www.cnblogs.com/gui8617788/p/3916027.html