当提供 IInspectable 作为 ComboBoxItem 的内容时,您应该能够使用 ToString() 函数提供显示字符串。但这个函数永远不会被调用,并且显示的只是一个空白框。
自定义IInspectable:
class ComboboxItem : public winrt::implements<ComboboxItem, winrt::Windows::Foundation::IInspectable>
{
public:
ComboboxItem() : m_text(L"Hello") {}
hstring Text() { return m_text; }
void Text(hstring const& value) { m_text = value; }
winrt::Windows::Foundation::IInspectable Value() { return m_value; }
void Value(winrt::Windows::Foundation::IInspectable const& value) { m_value = value; }
hstring ToString() cons { return m_text; } // This is never called
private:
hstring m_text;
winrt::Windows::Foundation::IInspectable m_value;
};
添加到组合框:
comboxBox.Items().Append(winrt::make<ComboboxItem>());
让字符串显示在组合框中缺少的“特殊酱汁”是什么?
我用 C# 实现,因为这是我让它工作的唯一方法。
using Microsoft.UI.Xaml.Controls;
namespace App2CSharp
{
internal class MyComboBoxItem : ComboBoxItem
{
public MyComboBoxItem()
{
Content = "TEST";
}
}
}
XAML:
<ComboBox x:Name="MyComboBox" Header="Colors" PlaceholderText="Pick a color" Width="200">
<x:String>Blue</x:String>
<x:String>Green</x:String>
<x:String>Red</x:String>
<x:String>Yellow</x:String>
<ComboBoxItem>Gray</ComboBoxItem>
</ComboBox>
还有
ComboBoxItem c = new MyComboBoxItem();
MyComboBox.Items.Add(c);