【问题标题】:Can't reference C++/cx class from xaml? (UWP)无法从 xaml 引用 C++/cx 类? (UWP)
【发布时间】:2016-03-02 14:22:39
【问题描述】:

我的应用程序中有一个 C++ 类testclient

namespace testclient{
    namespace models{
        ref class myclass sealed{
            public:
                 myclass();
                 property String^ getstring
                 {
                    String^ get()
                    {
                        return string;
                    }
                 }
            private:
                 String^ string = "test";
 }}}

我想将控件绑定到属性getstring,根据我对 UWP XAML 数据绑定的了解,我必须将其包含在 MainPage.xaml 的顶部:xmlns:data="using:testclient.models 问题是,智能感知是告诉我“未定义的命名空间。‘使用’URI 引用了一个名为 testclient.models 的命名空间,但找不到该命名空间。”我做错了什么?

编辑:当我将类放在 Mainpage.Xaml.h 中时,我发现问题消失了,但我宁愿不这样做......

【问题讨论】:

    标签: xaml data-binding uwp c++-cx


    【解决方案1】:

    每个绑定都包含一个绑定目标和一个绑定源。通常,目标是控件或其他 UI 元素的属性,源是类实例的属性。

    如果您想使用 myclass 作为 MainPage 的 UI 元素的数据源,您需要确保 mainPage 可以访问 myclass 的实例。这就是您的第一个版本导致错误的原因。为了尽可能少地修改 mainPage.Xaml.h,您可以按照以下步骤创建一个单独的文件(我简化了 myclass 的成员以便于调试):

    1) 创建 myclass.h:

    namespace TestClient{
        namespace models{
            public ref class myclass sealed
            {
            private:
                int test = 1;
    
            public:
                myclass()
                {
    
                }
    
                property int gettest
                {
                    int get() { return test; };
                }
            };
        }
    }
    

    2) 在 MainPage.h 中,添加以下内容:

    #include "myclass.h"
    
    namespace TestClient
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public ref class MainPage sealed
        {
        private:
            TestClient::models::myclass myTest;
       .......
        }
      .........
    }
    

    3) 然后您可以根据需要操作 mainPage.cpp 中的 myclass 数据。代码可能如下:

    MainPage::MainPage()
    {
        InitializeComponent();
        int i = this->myTest.gettest;
        ...........
    }
    

    我还有一个问题:虽然嵌套了这么多命名空间?您也可以在此处找到有关数据绑定的sample,仅供参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-23
      • 2018-02-07
      • 2020-09-07
      • 2018-02-06
      • 2013-03-19
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多