我有一个 DeviceSelector 类,它显示要选择的设备列表。我想以编程方式执行此操作,而不使用 XAML 文件。由于我发现很难从 C++ 中正确使用 ListBox 控件,因此我有以下问题:
- 如何正确使用该属性在 ListBox
DisplayMemberPath
中显示该属性?Name
应该传入属性的路径,但由于某种原因,这似乎在我的程序中不起作用。 - 是否可以使用该
ItemsSource
属性使用 Collection 填充 ListBox?从文档中不清楚将什么作为参数传递,并且没有那么多非 XAML C++ 示例。
下面我有我简化的 DeviceSelector 类,并提供了一个简单的应用程序用于故障排除。
编辑1:
DisplayMemberPath 没有像我期望的那样工作,并不是特定于 C++/WinRT。我尝试使用 XAML 和后面的代码来实现它,使用:
<ListBox x:Name="DeviceSelector" DisplayMemberPath="Name">
...
</ListBox>
用设备填充 ListBox 后,它也不显示名称。
设备选择器.h
#pragma once
#include <winrt\Windows.Foundation.h>
#include <winrt\Windows.UI.Xaml.Controls.h>
struct DeviceSelector : winrt::Windows::UI::Xaml::Controls::ListBox
{
DeviceSelector();
winrt::Windows::Foundation::IAsyncAction ShowAllAsync();
};
设备选择器.cpp
#include "pch.h"
#include "DeviceSelector.h"
#include <winrt\Windows.Devices.Enumeration.h>
#include <winrt\Windows.Foundation.h>
#include <winrt\Windows.UI.Xaml.Controls.h>
using namespace winrt::Windows::Devices::Enumeration;
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::UI::Xaml::Controls;
DeviceSelector::DeviceSelector()
{
//DOES NOT WORK:
//DisplayMemberPath(L"Name");
}
IAsyncAction DeviceSelector::ShowAllAsync()
{
DeviceInformationCollection devices = co_await DeviceInformation::FindAllAsync();
//DOES NOT WORK:
//ItemsSource(devices);
//DOES WORK:
//But does not display device names, without the right DisplayMemberPath.
for (DeviceInformation device : devices)
{
Items().Append(device);
}
}
主文件
#include "pch.h"
#include <winrt\Windows.ApplicationModel.Activation.h>
#include <winrt\Windows.UI.Xaml.h>
#include "DeviceSelector.h"
using namespace winrt;
using namespace winrt::Windows::ApplicationModel::Activation;
using namespace winrt::Windows::UI::Xaml;
struct App : ApplicationT<App>
{
DeviceSelector selector;
void OnLaunched(LaunchActivatedEventArgs const &)
{
//Create window with a DeviceSelector instance.
Window window = Window::Current();
window.Content(selector);
window.Activate();
//Populate selector with devices.
selector.ShowAllAsync();
}
static void Initialize(ApplicationInitializationCallbackParams const &)
{
make<App>();
}
static void Start()
{
Application::Start(App::Initialize);
}
};
int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int)
{
App::Start();
}
pch.h
#pragma once
#pragma comment(lib, "windowsapp")
#include <winrt\Windows.ApplicationModel.Activation.h>
#include <winrt\Windows.Devices.Enumeration.h>
#include <winrt\Windows.Foundation.h>
#include <winrt\Windows.Media.Devices.h>
#include <winrt\Windows.UI.Xaml.h>
#include <winrt\Windows.UI.Xaml.Controls.h>