【问题标题】:C# winforms 'Control' does not contain a definition for 'BorderStyle'C# winforms \'Control\' 不包含 \'BorderStyle\' 的定义
【发布时间】:2023-01-21 19:11:53
【问题描述】:

我正在使用 VS 2022 创建一个 winforms 应用程序并收到上述错误。
检查 MSDN 没有名为 BorderStyle 的控件属性。相反,BorderStyle 文档位于 Windows 桌面 6 下。

这是我的代码:

using System.Drawing;
using System.Windows.Forms;

namespace Library
{
    public class Styles : Form
    {
        public static void Label_as_Button_Enable(Control ctrlName)
        {
            ctrlName.BackColor = Color.FromArgb(214, 206, 165);
            ctrlName.ForeColor = Color.FromArgb(0, 0, 0);
            ctrlName.BorderStyle = BorderStyle.FixedSingle;
            ctrlName.Font = new Font("Segoe UI", 8, FontStyle.Bold);
            ctrlName.Enabled = true;
            ctrlName.Cursor = Cursors.Hand;
        }

所有其他属性正在编译。查看 Designer 文件,我发现“controlName”.BorderStyle = 等,所以当这不起作用时我感到很惊讶。我应该使用什么来代替Control
谢谢你。

【问题讨论】:

  • Control 类是所有控件(以及Form)的基类。并非所有东西都有边框样式。如果你想改变按钮的边框样式,你可以做类似if (ctrlName is Button btn) { /* same code, but using btn, not ctrlName */ }的事情
  • 如有疑问,请查看文档:Control Class
  • fyi @Flydog57 - Button 没有 BorderStyle 属性。 OP 正在创建一种方法,使 Label 看起来像一个按钮,或者至少这就是方法名称所暗示的。
  • 哦,各种情况下的字母混乱 (LBLasBTN) 是 LabelAsButton。我刚刚认出了 BTN 部分(我的眼睛确实注意到了 Las
  • 我很抱歉;我认为我的介绍性陈述清楚地表明,在发布问题之前我查阅了相关的 MSDN 文档。我会在未来尝试更明确。您的链接将我带到我查阅过的页面之一,甚至根据您在下面提供的解决方案重新阅读它,我不可能根据文档中提供的材料得出这些解决方案。 (是的,我正在使标签看起来/表现得像一个按钮)

标签: c# winforms


【解决方案1】:

WinForm Control 只是所有 WinForm 控件的公共基类:read the docs。并非所有 WinForm 控件都具有边框/边框样式。

如果您想使用通用方法设置边框样式,有几个选项。

反射

使用反射在这里基本上是一个包罗万象的方法,并且只会在存在边框样式属性时设置边框样式:

public static void LBLasBTN_Enable( Control ctrl )
{
    ctrl.BackColor = Color.FromArgb( 214, 206, 165 );
    ctrl.ForeColor = Color.FromArgb( 0, 0, 0 );
    ctrl.Font = new Font( "Segoe UI", 8, FontStyle.Bold );
    ctrl.Enabled = true;
    ctrl.Cursor = Cursors.Hand;

    PropertyInfo pi = ctrl.GetType().GetProperty( "BorderStyle", BindingFlags.Public | BindingFlags.Instance );
    if( pi != null )
    {
        pi.SetValue( ctrl, BorderStyle.FixedSingle );
    }
}

铸件

或者,可以将控件转换为您希望具有边框样式的任何类型:

public static void LBLasBTN_Enable( Control ctrl )
{
    ctrl.BackColor = Color.FromArgb( 214, 206, 165 );
    ctrl.ForeColor = Color.FromArgb( 0, 0, 0 );
    ctrl.Font = new Font( "Segoe UI", 8, FontStyle.Bold );
    ctrl.Enabled = true;
    ctrl.Cursor = Cursors.Hand;

    if( ctrl is Label lbl )
    {
        lbl.BorderStyle = BorderStyle.FixedSingle;
    }

    // add other types as needed...
}

就个人而言,我有点懒惰,只会走反思路线。但是,如果你想完全明确,那就去铸造路线。

【讨论】:

  • 我还没有深入研究 Reflection(虽然我可能正在接近那个阶段)但是 Casting 方法工作得很好。感谢您的时间和专业知识。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多