即使连接了控制器,UWP Gamepad.Gamepads 还是空的

UWP Gamepad.Gamepads is empty even though a controller is connected

我目前正在开发一个 UWP 应用程序,我希望能够从无线 xbox 控制器获取输入,但是,每当我尝试在我的代码中访问它时,我都会收到错误 System.InvalidOperationException: 'Sequence contains no elements'

我知道控制器已连接,因为它显示在我的蓝牙设备中,我可以在 Steam Big Picture 和游戏中毫无问题地使用它。我正在尝试使用此代码访问控制器:

var controller = Gamepad.Gamepads.First();
var reading = controller.GetCurrentReading();

我是漏了什么还是做错了什么?

I want to be able to take input from a wireless xbox controller however, whenever I try and access it in my code, I get the error System.InvalidOperationException: 'Sequence contains no elements'.

来自official document

the gamepad list is initally empty and will not list gamepads even if they are already connected. After a short period this will return a complete list of gamepads.

对于这种情况,您可以通过 Gamepad.GamepadAdded 事件列出所有连接的游戏手柄。

public MainPage()
{
    this.InitializeComponent();
    Gamepad.GamepadAdded += Gamepad_GamepadAdded;
}

private void Gamepad_GamepadAdded(object sender, Gamepad e)
{
    var controller = Gamepad.Gamepads?.First(); 
    var reading = controller.GetCurrentReading();
}