C++/WinRT Data Binding Two Way Confusion.

Ryan Gallagher 21 Reputation points
2020-09-08T02:48:49.46+00:00

Okay lets see if I get this right. Up to this point I have this figured out.

With binding I need to
Create a struct in the namespace of MyApp::implimentation that has the member variable I wish to expose and update. With methods to set and get said member.

Pipe it through a ViewModel struct that consolidates everything from the initial struct that can call those methods and return it to the MainPage

import the first struct into the view model struct then impliment that into the IDL file for the main page to construct the final viewmodel that can then be used by the XAML controls for binding...

Okay IF I have that right I was wondering if anyone could write a bare bones implementation of two way binding so that I can see what it is I am missing.

Do I need the intermediary viewmodel of can I directly implement the original data struct straight to the mainpage?

I know the answer is staring me right in the face and I am over thinking all of this.

Thank you.

Universal Windows Platform (UWP)
{count} votes

1 answer

Sort by: Most helpful
  1. Fay Wang - MSFT 5,196 Reputation points
    2020-09-08T08:38:32.027+00:00

    Hello,

    Welcome to Microsoft Q&A!

    As you mentioned, if you want to implement the two-way binding, you could declare a class which contains properties and implements INotifyPropertyChanged interface. After that, import a viewmodel which contains the class to the Mainpage and implement binding. It is better to use viewmodel to achieve code separation and below are the detailed steps about it.

    1.Create an IDL file named BookSku to store the binding source in your C++/WinRT project

    BookSku.idl

    namespace DataBindingSample  
    {  
        runtimeclass BookSku : Windows.UI.Xaml.Data.INotifyPropertyChanged  
        {  
            String Title;  
        }  
    }  
    

    2.Implement BookSku with a struct that has the member variable you wish to expose and update

    3.Declare and implement BookstoreViewModel to contain the BookSku and consolidate everything from the initial struct that can call those methods and return it to the MainPage

    4.Add a property of BookstoreViewModel to MainPage with a “import” statement

    MainPage.idl

    import "BookstoreViewModel.idl";  
    
    namespace Bookstore  
    {  
        runtimeclass MainPage : Windows.UI.Xaml.Controls.Page  
        {  
            MainPage();  
    
            BookstoreViewModel MainViewModel{ get; };  
        }  
    }  
    

    5.Bind the TextBox to the Title property with TwoWay mode.

    <TextBox x:Name="box" Text="{x:Bind MainViewModel.BookSku.Title, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />  
    

    For more detailed information, you can refer to the document and here is a simple sample that I created you can also check it.