Using compiled bindings in your Windows 10 universal app

One of the news in the Windows 10 SDK is that you can use compiled binding. In pre Windows 10 bindings was created in run time. When you're building your windows universal app for windows 10 you can created bindings in compile time. This to boost the performance of the bindings, compiled bindings will make the page load much faster. This blog post will introduce you with the basics of compiled bindings.

To create a binding that will be created in compile time you will use x:Bind instead of Binding to create the binding.

      

One big difference against is that the binding will not be to DataContext, it will be to the page. If the code above should work you have to create a Title property in the code behind file. If you don't do that you will get a error when you compiling your app. The reason to to bind to the actuall page instead of DataContext is that DataContext is of type object and the compiler will not know what you will assign to it during run time. Because you binding to the actual page it is also possible to bind directly to other controls on your page.

If you using a binding in a data template you have to specify data type for the data template with x:DataType as in the code below. Don't forget to declare the namespace for your data type. In this example I have created a property in my code behind file called ViewModel that has a Items property that I binding to the ItemsSource of the ListView.

  
            
                
                        
                    
                
            
        

The code behind can looks like the code below. In this example DataContext is set when the view is created and the ViewModel will have a method for loading data.

public sealed partial class ItemsView
{
        protected ItemsViewModel ViewModel { get { return DataContext as ItemsViewModel; } }

        public ItemsView()
        {
            this.InitializeComponent();
            DataContextChanged += ItemsView_DataContextChanged;
        }

        private async void ItemsView_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
        {
            if(ViewModel != null)
            {
                await ViewModel.LoadData();
            }
        }
}

  5/2/2015 - 5:16 PM