【问题标题】:Working with Resources and User-defined Control Properties使用资源和用户定义的控件属性
【发布时间】:2011-11-29 01:35:18
【问题描述】:

我正在创建一个自定义控件,它是一个按钮。根据其类型,它可能有一个类型和一个指定的图像。它的类型可能是:

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枚举,无需更改此方法。

如何实现此方法以兼容未来的变化?

【问题讨论】:

  • ChangeButtonType 方法在哪里?它在您的自定义按钮上吗?
  • @Anna:是的,它是一个控件库,这个方法和枚举都在那里。

标签: c# winforms coding-style methods


【解决方案1】:

您可以做的一件事是将ButtonType 转换为基类(或接口,如果您愿意):

public abstract class ButtonType
{
    public abstract Image GetImage();
}

然后你的每一个类型变成一个子类:

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 基类以类似的方式设置按钮行为(即它们被单击时执行的操作),并在您想要更改按钮的用途和样式时分配特定的操作,例如停止和播放。

【讨论】:

    【解决方案2】:

    不知道这是否是最佳选择,但您可以为您的枚举创建一个自定义属性,其中包含图像

    public enum ButtonType
    {
        [ButtonImage(CustomButtonLibrary.Properties.Resources.PauseButton)]
        PAUSE,
    
        [ButtonImage(CustomButtonLibrary.Properties.Resources.PlayButton)]
        PLAY
    }
    

    我不会对此进行详细介绍,因为这很容易在 Google 上搜索...事实上,这是一个很好的入门资源:

    http://joelforman.blogspot.com/2007/12/enums-and-custom-attributes.html?showComment=1317161231873#c262630108634229289

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多