0
我是新來的c#,我試圖創建一個ButtonImage控件。我已經設法讓大部分代碼運行,包括TextAlignment和圖像資源選擇,但圖像不會顯示。我已經嘗試添加TextImageRelation屬性以及ImageAlignment屬性不起作用 - 甚至不知道我是否已經正確地做了一切。我花了幾個小時搜索MSDN和互聯網,請幫忙,TNX。繼承人的代碼:獲取圖像顯示在自定義ButtonImage控件c#
namespace ImageButton
{
//[System.ComponentModel.DefaultBindingProperty("ButtonText")]
public partial class ImageButton : UserControl
{
private String name = "btn1";
private String btnText = "Button1";
private TextImageRelation textImage = TextImageRelation.Overlay;
private ContentAlignment alignmentValue = ContentAlignment.MiddleRight;
private ContentAlignment imageAlignmentValue = ContentAlignment.MiddleLeft;
public ImageButton()
{
InitializeComponent();
}
//
// Properties
//
[Description("Sets the Text Label"),
Category("Custom")]
public String ButtonText
{
get
{
return btnText;
}
set
{
btnText = value;
btn1.Text = btnText;
}
}
[Description("Sets the Button Image"),
Category("Custom")]
public Image Image
{
get;
set;
}
[Description("Specifies the relationship of text to Image."),
Category("Custom")]
public TextImageRelation TextImageRelation {
get{
return textImage;
}
set{
textImage =value;
btn1.TextImageRelation = textImage;
}
}
[Category("Custom"),
Description("Specifies the alignment of text.")]
public ContentAlignment TextAlignment
{
get
{
return alignmentValue;
}
set
{
alignmentValue = value;
btn1.TextAlign = alignmentValue;
//Invalidate();
}
}
[Category("Custom"),
Description("Specifies the alignment of text.")]
public ContentAlignment ImageAlignment
{
get
{
return imageAlignmentValue;
}
set
{
imageAlignmentValue = value;
btn1.ImageAlign = imageAlignmentValue;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
StringFormat style = new StringFormat();
style.Alignment = StringAlignment.Far;
switch (alignmentValue)
{
case ContentAlignment.MiddleLeft:
style.Alignment = StringAlignment.Near;
break;
case ContentAlignment.MiddleRight:
style.Alignment = StringAlignment.Far;
break;
case ContentAlignment.MiddleCenter:
style.Alignment = StringAlignment.Center;
break;
}
// Call the DrawString method of the System.Drawing class to write
// text. Text and ClientRectangle are properties inherited from
// Control.
e.Graphics.DrawString(
Text,
Font,
new SolidBrush(ForeColor),
ClientRectangle, style);
}
}
}