I am mapping an xbox controller and want a way for the user to change what key does what in the program. I use a dictionary with the key as a ControllerEventArgs ( custom event args) and value is Action, which is the function that will be invoked when the button is pressed.
Everything is in place except one part: We are able to open a combo box with all they buttons (A Pressed, A Released, B, X, Y, etc) and using reflection and attributes I display all the possible methods (actions) the button can make. So the user goes ahead and chooses it - But now I have the method name in the MethodInfo[] and I need it as an Action to pass to/modify my dictionary. Any way to do this? I am new to reflection and attributes.
Dictionary is defined as:
public Dictionary<ControllerEventArgs, Action<object>> ButtonMapping =
new Dictionary<ControllerEventArgs, Action<object>>(new ControllerComparison());
This is my event for when a button is pushed:
private void basicevent(object source, ControllerEventArgs e)
{
if (!AltState)
{
if (ButtonMapping.ContainsKey(e))
{
ButtonMapping[e].Invoke(e);
}
else //debug
{
MessageBox.Show("Key not found in dictionary.\nButton Name: " + e.Name + "\nAction: " + e.Action + "\nAlt Mode: FALSE");
}
}
else
{
if (AltButtonMapping.ContainsKey(e))
{
AltButtonMapping[e].Invoke(e);
}
else //debug
{
MessageBox.Show("Key not found in dictionary.\nButton Name: " + e.Name + "\nAction: " + e.Action + "\nAlt Mode: TRUE");
}
}
}
And this is where I am trying to modify the value of the dictionary ( You can see my commented out stuff I was trying near the bottom)
private void SaveKeyMapping_Click(object sender, RoutedEventArgs e)
{
ComboBoxItem item = (ComboBoxItem)KeySelection.SelectedItem;
string SelectedItem = item.Content.ToString();
string SelectedAction = AvailableActions.SelectedItem.ToString();
AvailableActions.Items.Clear();
CurrentAction.Items.Clear();
if ((SelectedItem == "RightThumb Moved") || (SelectedItem == "LeftThumb Moved"))
{
//Joystick specific
}
else if ((SelectedItem == "RightTrigger Pressed") || (SelectedItem == "RightTrigger Released") || (SelectedItem == "LeftTrigger Pressed") || (SelectedItem == "LeftTrigger Released"))
{
//Trigger specific
}
else
{
//Button specific
string[] SelectedButton = SelectedItem.Split(SelectedItem[1]);
ControllerEventArgs args = new ControllerEventArgs { Name = SelectedButton[0], Action = SelectedButton[1] };
//Convert MethodInfo to Action<object>....
// Action<object> action = (Action<object>)Delegate.CreateDelegate(typeof(Action<object>), ButtonMethods[1]);
//Action<object> ac = delegate(object instance) { ButtonMethods[0].Invoke(instance, null); };
// Action ac = (Action)Delegate.CreateDelegate(typeof(Action), ButtonMethods[1]);
Action<object> newaction = controller.LightControl;
//change value in dictionary
controller.ButtonMapping[args] = newaction;
}
}