C# 使用资源和用户定义的控件属性
我正在创建一个自定义控件,它是一个按钮。它可能有一个类型和根据其类型指定的图像。其类型可能是:C# 使用资源和用户定义的控件属性,c#,winforms,coding-style,methods,C#,Winforms,Coding Style,Methods,我正在创建一个自定义控件,它是一个按钮。它可能有一个类型和根据其类型指定的图像。其类型可能是: public enum ButtonType { PAUSE, PLAY } 现在,我可以使用以下方法更改其外观和图像: public ButtonType buttonType; public void ChangeButtonType(ButtonType type) { // change button image if (type == ButtonType.
public enum ButtonType
{
PAUSE,
PLAY
}
现在,我可以使用以下方法更改其外观和图像:
public ButtonType buttonType;
public void ChangeButtonType(ButtonType type)
{
// change button image
if (type == ButtonType.PAUSE)
button1.Image = CustomButtonLibrary.Properties.Resources.PauseButton;
else if (type == ButtonType.PLAY)
button1.Image = CustomButtonLibrary.Properties.Resources.PlayButton;
buttonType = type;
}
好的,这个方法看起来不太好,例如,也许以后我希望有另一个类型STOP
,例如对于这个按钮,我只想将它的图像添加到资源中,并将它添加到ButtonType
enum,而不改变这个方法
如何实现此方法以与将来的更改兼容?不知道这是否是最佳选项,但您可以为包含映像的枚举创建自定义属性
public enum ButtonType
{
[ButtonImage(CustomButtonLibrary.Properties.Resources.PauseButton)]
PAUSE,
[ButtonImage(CustomButtonLibrary.Properties.Resources.PlayButton)]
PLAY
}
我不会详细讨论这个,因为这很容易用谷歌搜索。。。事实上,这是一个很好的开始:
您可以做的一件事是将
ButtonType
转换为基类(或接口,如果您愿意):
然后,每个类型都成为一个子类:
public class PauseButtonType : ButtonType
{
public Image GetImage()
{
return CustomButtonLibrary.Properties.Resources.PauseButton;
}
}
public class PlayButtonType : ButtonType
{
public Image GetImage()
{
return CustomButtonLibrary.Properties.Resources.PlayButton;
}
}
然后,图像更改方法变为:
private ButtonType buttonType; // public variables usually aren't a good idea
public void ChangeButtonType(ButtonType type)
{
button1.Image = type.GetImage();
buttonType = type;
}
这样,当您想要添加另一个类型时,您可以添加另一个ButtonType子类,并将其传递给ChangeButtonType
方法
由于此方法位于自定义按钮类上,我可能会进一步将其封装在类中:
public class ButtonStyle
{
// might have other, non-abstract properties like standard width, height, color
public abstract Image GetImage();
}
// similar subclasses to above
然后在按钮本身上:
public void SetStyle(ButtonStyle style)
{
this.Image = style.GetImage();
// other properties, if needed
}
您可以使用ButtonAction基类以类似的方式设置按钮行为(即单击按钮时执行的操作),并在需要更改按钮的用途和样式时指定特定的操作,如停止和播放。ChangeButtonType方法在哪里?它在你的自定义按钮上吗?@Anna:是的,它是一个控制库,这个方法和那个枚举以及所有的都在那里。
public void SetStyle(ButtonStyle style)
{
this.Image = style.GetImage();
// other properties, if needed
}