在不支持字体的控件上设置字体

Setting fonts on controls that do not support a font

这里使用的是CF 2.0。为了支持多种语言,我在创建表单时为每个控件设置了字体(使用递归函数)。我发现有些控件根本不支持字体 属性,所以代码如下:

cntrl.Font = new Font("Tahoma", 12.0f, FontStyle.Regular);

抛出 NotSupportedException 异常。连呼:

if (cntrl.Font != null)

抛出相同的异常。为了解决这个问题,我编写了一个辅助函数,如下所示:

private static bool DoesControlSupportFont(Control cntrl)
{
    // Some control's do not support the Font property
    bool bSupported = true;
    if ((cntrl is HScrollBar) ||
        (cntrl is Panel) ||
        (cntrl is PictureBox) ||
        (cntrl is ProgressBar) ||
        (cntrl is TrackBar) ||
        (cntrl is VScrollBar))
        bSupported = false;

    return bSupported;
}

这可行,但似乎效率低下且有点不雅致。这是处理不支持字体的控件的推荐方法吗?也许有更有效的方法(比如使用 try-catch 块并处理异常)?

除了你已经提到的那些,我认为没有其他可行的选择来解决这个问题。

在完整框架中,您可以测试 [Browsable(false)] 属性,以获得您打算使用的内容的指示。此信息已从 Compact Framework 程序集中删除。

如果我是你,我至少会把你现有的代码放在 try/catch 块中,特别是捕获 NotSupportedException,这样以后的控件就会自动覆盖(任何人都可以继承 Control ).

我也会留下硬编码检查,因为这些情况并非完全例外。

PS。 运行 进入 this link 前段时间,解释了如何从 CF 设计器 "hide" 属性。