简体   繁体   中英

Firing Actions from combobox.selectedvalue with c# windows forms

Here is my dictionary with strings and actions defined

SortedDictionary<string, Action> buttonoptions = new SortedDictionary<string, Action>
{
      {"Left Click", DoMouseClick()},
      {"Right Click", DoRightMouseClick()},
      {"Windows Key", wKey()}
};

abuttonCombo.DataSource = new BindingSource(buttonoptions, null);
abuttonCombo.DisplayMember = "Key";
abuttonCombo.ValueMember = "Value";

And here is where i want to run the relevant action:

if (stateOld.Gamepad.Buttons != GamepadButtonFlags.A && stateNew.Gamepad.Buttons == GamepadButtonFlags.A)
{
    //run the relevant action from the comboBox.SelectedValue
} 

How would i accomplish this?

First, make sure you create Action within the SortedDictionary with new Action .

    SortedDictionary<string, Action> buttonoptions = new SortedDictionary<string, Action>
    {
          {"Left Click", new Action(DoMouseClick)},
          {"Right Click", new Action(DoRightMouseClick)},
          {"Windows Key",new Action(wKey)}
    };
    comboBox1.DataSource = new BindingSource(buttonoptions, null);
    comboBox1.DisplayMember = "Key";
    comboBox1.ValueMember = "Value";

Create the methods DoMouseClick, DoRightMouseClick and wKey, each returning void.

private void wKey()
{
}

private void DoRightMouseClick()
{
}

private void DoMouseClick()
{
}

Finally, you can use dynamic to get the Action and run it. Make sure you use SelectedItem and not SelectedValue .

    dynamic selection = comboBox1.SelectedItem;
    var selectionMethod = selection.Value;
    selectionMethod();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM