【问题标题】:UWP - Bind a Vector to a ComboBox in c++UWP - 在 C++ 中将向量绑定到组合框
【发布时间】:2017-10-23 08:53:53
【问题描述】:

我的 UI 中有一个组合框。在我的网络类中,我有一个接收 udp 数据包并从中获取 IP 地址的方法。我应该采用哪种数据类型将地址保存为字符串(Vector、IVector?)。以及如何将具有地址的这个对象连接到 UI 中的组合框 - 因此每个地址都动态显示在组合框中。 我将 c++ 用于网络类,将 xaml + c++ 用于 UI。为避免混淆,我使用 Visual Studio 2017 中的 UWP-XAML-C++ 模板。

【问题讨论】:

    标签: xaml vector combobox uwp c++-cx


    【解决方案1】:

    我应该采用哪种数据类型将地址保存为字符串(Vector、IVector?)

    是的,Vector 可以用作与ComboBox 的集合绑定。更多C++/CX合集请参考this document

    以及如何连接这个具有地址的对象

    为此,我们需要使用data binding

    例如,假设有一个network类包含IpAddress属性如下:

    MainPage.xaml.h 中的代码

    public ref class MainPage sealed
    {
    public:
        MainPage();
    private:
        void btnbinding_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
    };
    
    public ref class network sealed
    {
    public:
        property Platform::String^ IpAddress;
    };
    

    然后我们可以将network集合(向量)绑定到ComboBox如下:

    XAML 代码

    <ComboBox x:Name="combo" >
        <DataTemplate>
            <TextBlock Text="{Binding IpAddress}"></TextBlock>
        </DataTemplate>
    </ComboBox>
    

    后面的代码

    void CombboxC::MainPage::btnbinding_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
        Platform::Collections::Vector<network^>^ items = ref new Platform::Collections::Vector<network^>();  
        network^ onenet = ref new network();
        onenet->IpAddress = "Test";
        items->Append(onenet);
        combo->ItemsSource = items; 
    }
    

    【讨论】:

    • 这不是我的意思,我在网络类中有一个循环,用于用地址填充向量。我不希望它被填写在后面的代码中。我最大的问题是如何在 c++ 中创建一个由 main-UI 类读取的全局向量。我知道如何在 java/c# 中执行此操作,但我未能在 c++ 中创建全局向量。
    猜你喜欢
    • 2016-02-22
    • 1970-01-01
    • 2013-12-24
    • 2018-11-04
    • 2013-05-21
    • 2012-11-12
    • 2018-11-12
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多