justanotherxl
justanotherxl

Reputation: 319

Can't reference C++/cx class from xaml? (UWP)

I have a C++ class in my application testclient:

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

I want to bind a control to the property getstring, and from what little I understand of UWP XAML data binding, I have to include this in the top of the MainPage.xaml: xmlns:data="using:testclient.models Problem is, intellisense is telling me "Undefined namespace. The 'using' URI refers to a namespace called testclient.models that could not be found." What am I doing wrong?

EDIT: I've found the problem goes away when I put the class in Mainpage.Xaml.h, but I'd rather not do this...

Upvotes: 0

Views: 712

Answers (1)

Fangfang Wu - MSFT
Fangfang Wu - MSFT

Reputation: 1072

Every binding consists of a binding target and a binding source. Typically, the target is a property of a control or other UI element, and the source is a property of a class instance.

If you want to use myclass as datasource to MainPage's UI elements, you need to make sure the instance of the myclass is accessible to MainPage. That's why your first version resulted in error. In order to modify mainPage.Xaml.h as little as possible, you could follow steps below by creating a separate file(I simplified the member of myclass for easy debugging):

1) Create 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) in MainPage.h, add following:

#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) Then you can manipulate myclass data in mainPage.cpp as you want. Codes may be like below:

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

Still I have a question: while so many namespace nested? Also you can find a sample about data binding here just for your reference.

Upvotes: 2

Related Questions