如何在表单事件C#中传递字典键?

问题描述 投票:1回答:1

这是我正在运行的代码:

private Dictionary<string, List<GuiEvent>> m_events = new Dictionary<string, List<GuiEvent>>();
        private void OnRadioBtnCheckedChange(object sender, EventArgs e, string formhandle)
        {
            RadioButton control = (RadioButton)sender;
            GuiEvent evnt = new GuiEvent
            {
                id = GuiEventType.RadioButtonChange,
                ElementName = control.Name,
                sparam = control.Text,
                lparam = control.Checked ? 1 : 0
            };
            m_events[formhandle].Add(evnt);
        }

获取错误:

Severity    Code    Description Project File    Line    Suppression State
Error   CS0123  No overload for 'OnRadioBtnCheckedChange' matches delegate 'EventHandler'   MtGuiController C:\Users\AIMS-RESEARCH\Desktop\MtGuiController\MtGuiController\Controller.cs    258 Active

以前是这样声明m_event的:

private List<GuiEvent> m_events = null;

和函数:

private void OnRadioBtnCheckedChange(object sender, EventArgs e)
{
    RadioButton control = (RadioButton)sender;
    GuiEvent evnt = new GuiEvent
    {
        id = GuiEventType.RadioButtonChange,
        ElementName = control.Name,
        sparam = control.Text,
        lparam = control.Checked ? 1 : 0
    };
    m_events.Add(evnt);
}

一切正常。我无法理解在这种情况下我能做什么。我无法将string formhandle声明为全局变量,因为每次都在更改。所以请记下它。它是C#DLL函数。

有人可以告诉我有帮助的解决方案吗?

c# winforms dll
1个回答
3
投票

如果要在事件处理程序中使用某些附加信息,则不能将其作为附加参数传递给事件处理函数。您也不能更改事件处理程序参数的类型-它应该只接受两个参数-senderEventArgs

您在这里有三个选择。首先-将数据存储在sender中,然后在事件处理程序中访问该数据。最简单的方法是使用单选按钮的标签。 Control.Tag是从Control基类继承的,创建控件时可以使用它存储一些数据。即为每个单选按钮formhandle分配适当的Tag(您甚至可以通过设计器手动完成此操作)

radioButton1.Tag = "foo";
radioButton2.Tag = "bar";

然后在事件处理程序中检索它:

    private void OnRadioBtnCheckedChange(object sender, EventArgs e)
    {
        RadioButton control = (RadioButton)sender;
        GuiEvent evnt = new GuiEvent
        {
            id = GuiEventType.RadioButtonChange,
            ElementName = control.Name,
            sparam = control.Text,
            lparam = control.Checked ? 1 : 0
        };
        var formhandle = (string)control.Tag; // here you get "foo" or "bar"
        m_events[formhandle].Add(evnt);
    }

第二个选项-创建您的自定义单选按钮控件。但这在这里太过分了。通常,在需要自定义外观时,您可以这样做,而不仅仅是传递数据。

第三选项-使用您拥有的数据(例如控件名称)查找数据。当控件创建时所需的数据不可用或随时间变化时,此选项才有意义。

© www.soinside.com 2019 - 2024. All rights reserved.