无法使用C++使ToString()为WinUI 3的ComboBoxItem的IInspectable内容工作

f0brbegy  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(85)

当为ComboBoxItem提供IInspectable作为内容时,您应该能够使用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;
};

添加到ComboBox:

comboxBox.Items().Append(winrt::make<ComboboxItem>());

让字符串在ComboBox中显示缺少的“特殊酱料”是什么?

axr492tv

axr492tv1#

我用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);

完成C++部分。

struct MyComboBoxItem : winrt::Microsoft::UI::Xaml::Controls::ComboBoxItem
{
    MyComboBoxItem() noexcept 
    {
        Content(box_value(L"TEST2"));
    }
};

XAML:

<ComboBox x:Name="ColorCombo" 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>

ColorCombo().Items().Append(box_value(L"TEST"));
MyComboBoxItem c{};
ColorCombo().Items().Append(c);

相关问题