Category Archives

Setting the device brightness on Windows with WPF

.NET, Technical stuff, Windows 10, Windows 7, Windows 8, Work, WPF
2 Comments

I am working on a project which I can’t really detail, but one aspect caused me a few headaches. Finally I reached out to the Windows team at Microsoft and got great help from Katie Anderson who works on the brightness team. This was quite tricky, and we had to have a couple of roundtrips before we managed to find a way that worked.

Well, why?

In the application I am working on, it is necessary for the user to set the device brightness from the application itself. You might wonder why, because most Windows devices have hard keys to set the monitor brightness. For example on a Surface, you can use the Fn-Del and Fn-Backspace key combinations to alter the brightness of the screen. Or you can of course swipe from the right side and use the Brightness button to change the value in the Action Center.

However on that particular project, the user doesn’t have access to the keyboard, nor to the Action Center. This is a kind of kiosk scenario if you will where many of the Windows features are deactivated by policies, and no hard keyboard is provided. I had to find a way to do this programmatically.

First approach: Not so good

At first I thought I would have my application’s main window run in full screen and set a black Rectangle on top of everything, and change the Rectangle’s opacity in my code. That worked well but of course it wouldn’t work if other applications were in the foreground (yes, I forgot to mention, it’s a kiosk app which can start other apps and put them in the foreground…).

Second approach: Better but not great

OK, no problems I thought, let’s have my app open a modal full screen window which is always on top. I will then have this window made insensitive to touch or mouse clicks with the following code. Finally, this window will have the black Rectangle and be on top of everything all the time.

public static class WindowsServices
{
    private const int GwlExstyle = -20;
    private const int WsExTransparent = 0x00000020;

    public static void SetWindowExTransparent(IntPtr hwnd)
    {
        var extendedStyle = GetWindowLong(hwnd, GwlExstyle);
        SetWindowLong(hwnd, GwlExstyle, extendedStyle | WsExTransparent);
    }

    [DllImport("user32.dll")]
    static extern int GetWindowLong(IntPtr hwnd, int index);

    [DllImport("user32.dll")]
    static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);
}

This worked OK but somehow it was not satisfying. I really wanted to have a solution where my app would modify the actual device brightness. There are a few reasons why the client also wanted that, and so I started to investigate deeper. Unfortunately, Bing searches (and the equivalent Google searches) didn’t really return anything satisfactory.

Using Powershell

After searching a bit, I got a first clue that what I wanted to achieve was doable: You can query and modify the device brightness from Powershell with the following script:

CODE TO GET THE BRIGHTNESS INSTANCE

PS C:> Get-Ciminstance -Namespace root/WMI -ClassName WmiMonitorBrightness

CODE TO SET THE BRIGHTNESS

PS C:\Users\lbugn> $monitor = Get-WmiObject -ns root/wmi -class wmiMonitorBrightNessMethods
PS C:\Users\lbugn> $monitor.WmiSetBrightness(50,10)

If you run these commands in Powershell, you will marvel at the result: Yes it does work and the screen’s brightness is modified. Great Scott, I am on the right track! The key to this is the WMI (Windows Management Interface) class WmiMonitorBrightness.

Converting to .NET

The next step was obvious: I needed to convert the Powershell script to some usable .NET code. Unfortunately, easier said than done. This is where I reached out to Microsoft for help and thankfully Katie really followed through and after a few iterations we got it to work.

First she used the WMI Code Creator tool to convert the Powershell script to .NET. I had no idea that such a tool existed, but then again I never had to dive so deep in the entrails of Windows. Unfortunately when running the code that the tool created (which I won’t post here to avoid confusion), I got some errors. One more roundtrip to Redmond (via email) and Katie found the way: The following code will indeed modify the brightness of the screen, yay!!

public static class WindowsServices
{
    private static ManagementObject _brightnessInstance;
    private static ManagementBaseObject _brightnessClass;

    static WindowsServices()
    {
        // Querying the Windows service to get the Brightness API.
        var searcher = new ManagementObjectSearcher(
            "root\\WMI", 
            "SELECT * FROM WmiMonitorBrightness");

        var results = searcher.Get();
        var resultEnum = results.GetEnumerator();
        resultEnum.MoveNext();
        _brightnessClass = resultEnum.Current;

        // We need to create an instance to use the Set method!
        var instanceName = (string)_brightnessClass["InstanceName"];
        _brightnessInstance = new ManagementObject(
            "root\\WMI",
            "WmiMonitorBrightnessMethods.InstanceName='" + instanceName + "'",
            null);
    }

    public static int GetDeviceCurrentBrightness()
    {
        // Getting the current value.
        var value = _brightnessClass.GetPropertyValue("CurrentBrightness");
        var valueString = value.ToString();
        return int.Parse(valueString); // Direct cast fails.
    }

    public static void SetDeviceBrightness(int newValue)
    {
        if (newValue < 0)
        {
            newValue = 0;
        }

        if (newValue > 100)
        {
            newValue = 100;
        }

        var inParams = _brightnessInstance.GetMethodParameters("WmiSetBrightness");
        inParams["Brightness"] = newValue;
        inParams["Timeout"] = 0;
        _brightnessInstance.InvokeMethod("WmiSetBrightness", inParams, null);
    }
}

I made a small sample here which gets the current value of the screen brightness and then increases it by 10% every time you click on a button. When you reach 100%, it goes back to zero on the next click. Simple enough, and does the trick.

I hope that this will be useful to a reader looking for the same feature. I’d love to be the first one to ever blog about this. I doubt that I am, and probably someone will point me to the article that I never found :) but seriously, I really couldn’t find any mention of something like that on the whole WWW.

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)

Share on Facebook
 

Two millions #mvvmlight downloads

.NET, MVVM, Technical stuff, Universal Windows Platform UWP, Work, WPF, Xamarin, XAML
3 Comments

Sometimes between last week and this week, we crossed a threshold: Two millions MVVM Light downloads.

I don’t have many metrics about MVVM Light, because the toolkit itself is not instrumented in any way. You get the raw binaries without added sugar :) So the only numbers I can rely on are the number of downloaded copies, either on Nuget or as the VSIX extension for Visual Studio. Obviously this doesn’t say much about the number of applications created with MVVM Light, since once the VSIX is downloaded, every File / New Project command creates a new app without any download. Still, it’s been interesting to see the evolution in downloads since I started to track the numbers.

Recently, I had a memory on my Facebook wall reminding me that 2 years ago, I was posting about 500’000 downloads, just before my Visual Studio Live sessions in Las Vegas. Two years later I was in Vegas again, for VS Live again, and about to cross two millions. Clearly the curve went up quite a bit. I tried to analyze what was the most significant change, and I think the port to Xamarin definitely played a significant role there. I also saw an uptake in interest in conference submissions since MVVM Light is truly cross platform, especially since Xamarin Evolve 2014 where I had a session. Since then a lot more sessions were given about Building Truly Universal Applications with MVVM Light, and quite a few full rooms too.

Tracking the downloads

As I mentioned, it is difficult to track downloads in a significant manner. There are automated build stations that will restore Nuget packages every so often. On the other hand there are people who download the Visual Studio extension once and create new applications without downloading anything. The only significant metric, I guess, is the evolution in downloads over time. Here is a chart (click to enlarge):

2017-03-21_11-13-37

Right now I track downloads on the following pages:

What’s coming

Currently I am working on the following topics:

  • A post about Working with MVVM Light in Visual Studio 2017. This is a pretty long post, which will also end up in the documentation pages. It will also explain how the sample applications (created by the templates) work and what features they demonstrate.
  • Improving the project template for WPF. I want to add more features there and be on par with what I have for Windows 10, iOS and Android.
  • Adding a project template for iPad and iOS Universal.
  • MVVM Light for Xamarin Pluralsight course. No ETA on this at the moment, sorry.

And of course the backlog is still active! Don’t hesitate to send your feedback :)

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Code and slides posted for my latest talks

.NET, Conferences, HoloLens, MVVM, Technical stuff, Universal Windows Platform UWP, UX, Windows 10, Work, Xamarin, XAML
No Comments

October and November have been quite busy with travel. I talked at a few occasions in some cool events and want to take a moment to share the code and slides below:

Xamarin Dev Day, Zurich, Switzerland

I love the concept of the Xamarin Dev Day. It’s a great way to reach out to local communities and have a day of fun teaching and training with Xamarin content. This year I took part to the Zurich, Switzerland occurrence. It definitely didn’t hurt that it was help in a very cool space, under a train viaduct in the previously industrial area of the city, which is these days a pretty cool place to live and work.

I held my talk titled “Building truly cross platform applications with Windows, Xamarin and MVVM Light” which comments on the fact that the so called “UWP” (Universal Windows Platform) applications are only for Windows (hence the W) and that if you want to target mobile iOS and Android devices, you need something more. Xamarin and MVVM Light are great solutions in this scenario, because they maximize the amount of code that can be shared, all the while increasing the testable surface of the application. You can find the code and slides at this page.

KC .NET User Group & Xamarin KC Dev, Kansas City, Missouri

You might have read that the company I joined in 2008 (IdentityMine) was acquired this year by a company based in Kansas City named Valorem Consulting. On November 1st and 2nd, I spent time at the head office to meet with a maximum of new colleagues. It was a nice stay in a city (and state) I had never visited before. In fact I even “visited” two states during that stay, because Kansas City is laid over Missouri and Kansas! Earlier on I had tweeted about me visiting KC, and the local .NET developer user group contacted me and asked if I wanted to speak at a user group meeting on that evening. Of course the answer was a resounding yes! And the best part is that the Xamarin KC user group also joined the fun for their first ever joint event. We had a great attendance with a full room of about 65 people, and a very nice interaction. After the event, a small group gathered at a local bar and we had pie and drinks (I had a root beer float, because why not). Excellent way to make new friends in a new city! I also held my talk “Building Truly Universal Applications with Windows, Xamarin and MVVM Light”.  You can find the slides and code here.

DevIntersection Europe, Haarlem, The Netherlands

Right after my return from the US (with the visit to Kansas City, a few days in the office in Seattle and then the MVP and Regional Directors Summit in Bellevue/Redmond), I had another short trip to the Netherlands. I spoke at the DevIntersection conference in Haarlem, a small city not far from Amsterdam. The location was superb, a convention center close to the historical center of the city, the hotel was great too (though the bed was wayyyyy too soft for me :) and the audience was very nice. It is definitely smaller than DevIntersection in the US (where they have events in Vegas and Orlando), but I had a good albeit small audience nonetheless and some great interactions with attendees and fellow speakers.

I spoke about the Windows 10 Universal Windows Platform, a dense session which contains information about creating a new UWP app; adapting the user interface to the various form factors, resolutions, orientations etc; porting classic windows applications to the Windows 10 ecosystem with the Desktop App Converter (also known as Centennial bridge); the Windows Continuum; and Microsoft HoloLens. Unfortunately because of unknown technical issues, I was not able to stream the HoloLens output to my phone nor to my Surface like I used to do. Unfortunately we ran out of time before I was able to solve the issue (which would probably have required restarting the HoloLens and the phone). I want to apologize to the audience for this technical glitch. I hope that the people who joined me later for a quick trial of the HoloLens were happy anyway, and that the others didn’t go back home with a bad image of this amazing technology :) I recorded a few videos showing the various demos I wanted to give, you can find all the material including code and slides on this page.

Thanks all for attending and happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

#Microsoft #Experiences in Paris: Code and slides

.NET, Conferences, HoloLens, MVVM, Technical stuff, Windows 10, Work, WPF, Xamarin, XAML
No Comments

Last week I had the pleasure of taking the TGV from Zurich to Paris, and after a quick 4 hours of comfortable travel, to make my way to the Porte Maillot and the Palais des Congrès.

TL;DR: All slides and source code is available from here.

A podcast

After a good night sleep I made my way to the speakers lounge and prepared the last steps for my talk. Then I took a moment to head to the meeting room where the Live Tiles podcast was being recorded. A band of podcasters got together and talked about the future of Microsoft. It was so nice to “see these familiar voices” in action. Even nicer when Christophe (Toss .NET) and Denis saw me and pulled me in to talk about HoloLens and our experiences with this device. You can hear the recording here, my contribution starts at 36:30.

My talk: Really universal apps with Xamarin and MVVM Light

My talk was titled (in French) “Construisons des applications vraiment universelles avec Windows, Xamarin and MVVM Light”. This favorite topic of mine shows how you can structure an application to share a maximum of code without any compromises. You can build healthy layers of Model and ViewModel, unit test them so you can feel secure about not breaking anything with future changes. Then you can build a thin layer of real native user interface for any supported framework with XAML or Xamarin (Windows Presentation Foundation, Windows 10 Universal, Xamarin.iOS, Xamarin.Android). And if you are in an enterprise scenario and looking for maximum productivity, you can also of course use Xamarin.Forms and render the same UI to all supported platforms.

The MVVM Light Toolkit assists you in these tasks, notably by providing a Data Binding framework for Xamarin.iOS and Xamarin.Android, as well as components that make it very easy to connect a list control to an ObservableCollection, with automatic refresh in case the collection changes. This open source toolkit is in it’s version 5.3, has been downloaded almost 1.7 million times and is even used by Microsoft to build parts of Windows 10.

I was really pleased when I headed to my conference room and saw a long queue in front of the entrance. I gave my talk to a standing room of about 270 people, and loved the interaction during and after the talk. A lot of very positive feedback, and we stayed and talked until the hostess kicked us out of the room :)

Thank you to everyone who came and made this a memorable moment. You will find all the details of the talk, the slides and the source code from this portal.

Some tea

Before I made my way to the Palais des Congrès, I took a pit stop at one of the most wonderful shops on Earth: the Mariage Frères tea store. This old fashioned store is stock full of amazing teas from all over the world. It’s a must-visit if you are a tea enthusiast or if you just want to spend a moment living in an atmosphere of luxury and pleasure.

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Slides and sample code for my presentations at #VSLive Boston

.NET, Conferences, Universal Windows Platform UWP, VSLive, Windows 10, Work, WPF, XAML
2 Comments

Thanks to everyone who came to my sessions at VSLive Boston. I had a great time. I hope it was informative and useful. I am aware that you take time out of your job to come and see us speak and I really hope that you found it worth your time.

I had two sessions:

Windows 10 – The Universal Application: One App To Rule Them All?

You can find the slides and sample code for this session here. This page also links to a video showing how Windows 10 Universal apps work on HoloLens!

Windows Presentation Foundation (WPF) 4.6

Here are the slides and sample code.

Thanks again for your warm welcome in Boston!! I even had some time to visit the city and had a blast in the historical places.

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Back from Sweden! Slides and code for my #DevSum16 session

.NET, Conferences, HoloLens, Technical stuff, Universal Windows Platform UWP, Windows 10, XAML
No Comments

I am back from Stockholm and the DevSum conference! It was a great trip, what a beautiful city and lovely people! It was great to be there with so many friends from our beautiful community, and especially my colleague and friend Rene Schulte.

On Thursday, I started by helping my good friend Tim Huckaby with his keynote. My role was very limited, just monitoring the live stream coming from Tim’s HoloLens. Tim is a great speaker and his keynote was very interesting and funny. So nice to see him! Later, Rene did a talk about HoloLens 3D development. Always a great pleasure to see Rene show how to use Unity and build 3D apps!

image6

On Friday, it was my turn to speak. I have a Windows 10 Universal session and I decided to spice it up with a few demos of new platforms. It was a bit scary because there were quite a few moving pieces, and everything had to play together perfectly. And it almost did! The only thing I didn’t think about is that the Continuum dock is “protected” with HDCP. That means that you cannot connect the Dock to a projector. Such an annoying (and useless) feature! Thankfully, the conference center where DevSum took place had awesome technicians, and one of them saved my day by connecting an HDMI-to-VGA adapter which circumvented the issue.

The talk was quite beefy: We defined what a Universal app is, then we talked about Adaptive UI. We discussed the Centennial and Islandwood bridges before talking about Continuum and HoloLens. The final demo saw me switch my presentation to my Windows 10 mobile phone (950XL), show some slides in Powerpoint, then demo some Universal apps on this platform. Finally I started the HoloLens application on my phone, in Continuum mode. Since this is also a Universal app, it adapted to the big screen beautifully and I could stream what I was seeing through my HoloLens. I demonstrated how universal applications run on the holographic platform, including our own apps. It’s just as simple as deploying them to the HoloLens!

image4

We definitely live exciting times, and it’s really great to be working on these new platforms. You can find the slides and sample code for this talk on my website. The session was recorded, and I will tweet when the recording is available for your viewing please, so stay tuned to my Twitter feed. Thanks to everyone who came to see this session. I really hope it was informative and useful to you!

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Slides and sample code for #XamarinEvolve and #Techorama

.NET, MVVM, Techorama, WPF, Xamarin, XAML
4 Comments

These past weeks have been busy with travel and speaking. After the wonderful time in San Francisco for Build 2016, I had a few precious weeks to prepare for Xamarin Evolve (Orlando, FL) and Techorama (Mechelen, Belgium). I just came back and here is the time to post the slides, sample code, and for Xamarin Evolve we even have a video of the talk!

Xamarin Evolve

2016-01-03_19-25-58

Evolve took place in tropical Orlando, and it was pretty nice to see sun, warm temperature and even some pool time on the day after the conference ended. I had a great time there. I talked about the DataBinding system in MVVM Light, which applies to Xamarin.iOS and Xamarin.Android. This critical part of all MVVM applications is there to ensure the connection between the ViewModel layer (typically in a portable class library and shared across all platforms) and the View layer. In Xamarin.Forms and on Windows, we don’t need an external databinding framework because we already have these (this is what you use when you write Text=”{Binding MyProperty}” in XAML). But in Android and iOS, there is no such concept, and this is where the MVVM Light platform-specific extensions come handy.

Here is the abstract (which was modified by Xamarin themselves… I normally don’t really use this marketing-y tone ;):

An In-Depth Study of the MVVM Light Databinding System

Living in the dark ages and still wiring up properties manually between your user interface and data source? Databinding is a technique to automatically synchronize a user interface with it’s data source and can vastly simplify how your app displays and interacts with data. While databinding is available out of the box for Xamarin.Forms and Windows applications, additional components are needed in Xamarin.Android and Xamarin.iOS. In this session, learn how to leverage databinding in your cross-platform applications as you master MVVM Light databinding and the MVVM pattern.

I created a page for this presentation on my website. There you will find the slides, video recording as well as the sample code.

Note: At the moment, some of the Xamarin Evolve videos are not working properly. Xamarin is informed. Thanks for your patience.

Techorama

techorama

Techorama is one of my favorite conferences, created by the community for the community after the cancellation of TechDays Belgium. Gill, Pieter and Kevin created a hell of a show, which grew to host more than 1000 visitors these days. The venue is awesome too, it is a movie theater and we get to project our slides and code on a huge screen. This year there were quite a few renowned speakers from the US and the whole world in fact. Even though I got to spend only one night at home after coming back from Orlando before flying again, which was quite tiring and a bit stressful, I was really looking forward to go to Mechelen. I hope you enjoyed my session there about WPF. It was a fun session where I talked about the differences between WPF and the Windows 10 Universal platform, about new development in WPF (especially tools such as the Visual Tree, the Live Property Explorer, and XAML Edit and Continue), about the Windows Bridge “Project Centennial” which takes a classic Windows app and “packs” it to transform it into a Universal application. We finished with an exciting demo of a new feature shown at Xamarin Evolve the week before: the Xamarin Workbooks, which allow you to create a rich document (using Markdown) with titles, subtitles, images etc, and allows including snippets of C# that will be executed by the Xamarin Inspector tool. Because the tool supports Android, iOS and WPF, it was a great find and it fitted well in my session which aimed to show that WPF is still very current and state of the art. So I happily changed my presentation to include it in the demos.

Windows Presentation Foundation (WPF) 4.6

Windows Presentation Foundation is what people are using to build real applications for the enterprise, the industry, the workplace, and for every situation where Windows 10 Universal is not quite ready yet. Far from being dead, WPF is 10 years old this year, alive and kicking, and gives Universal Applications a run for their money! In this session, Laurent Bugnion, a Microsoft Windows Developer MVP and Microsoft Regional Director, WPF expert since 2006, will show you what is new in Windows Presentation Foundation, where it is going in the future, and what you can achieve with WPF that Universal Application developers can only dream of.

The presentation’s page is on my website, and will give you access to the slides and the demo source code. Make sure to check the last couple of slides for more resources!

One more thing

I recently discovered (not sure how I missed that) that my session about Windows 10 UWP at the Future Decoded conference in London last year had been recorded. I added the video to the presentation’s page. So in case you want to know how to adapt your UWP app on multiple platforms, this is where you can go!

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
 

Releasing MVVM Light V5.3 to Nuget

.NET, MVVM, Work, Xamarin, XAML
9 Comments

With Xamarin Evolve coming up (I am currently on the way to Orlando!), it was time to release a new version and take care of a few bugs, improvements and new features.

Update: To be clear I didn’t remove the Windows 8.1 version, it is still available! Only the Windows 8 version is removed.

In version 5.3, the majority of the activity was on the data binding system for Xamarin.iOS and Xamarin.Android, with many improvements in stability and performance, as well as a few new features. Existing code will continue to work as is, and at most you might have a few “deprecated” warnings, which will give you time to update your code. I also added 3 classes and a few helpers around them, which should help you greatly when you work with lists: ObservableRecyclerAdapter (for Android RecyclerView), ObservableTableViewSource (for iOS TableView) and ObservableCollectionViewSource (for iOS CollectionView). These objects will be detailed in separate blog posts.

In other areas not directly Xamarin-related, you will also find quite a few bug fixes. Here is list of changes. You will also find a few explanations below. I will publish additional blog posts with more details about the Observable list components mentioned above.

Removed old frameworks

In a desire of simplification, I removed the Silverlight 4, Windows Phone 7.1 and Windows 8 versions of MVVM Light from the repo. This does NOT affect the Silverlight 5, Windows Phone 8.0 and 8.1, Windows 8.1 as well as Windows 10 of course which are still very well supported. The main reason for not supporting these older versions is that they require Visual Studio 2012 and cannot be maintained or tested in VS2015. I hope that this doesn’t affect your projects too much. Should that be the case, please send me a note. We can always find a solution!

Fixing Nuget install.ps1 and documentation

There was a silly bug in the install.ps1 script that is run after the Nuget installation is performed, it is fixed now. Also, I added a more explicit description of the packages mvvmlight and mvvmlightlibs, in order to underline the differences between both.

Documentation: Closures not supported

In the same vein, I added explicit documentation warning that closures are not supported in the Messenger Register method, as well as in the RelayCommand Execute and CanExecute delegates. This is sometimes an issue. The reason is that these components are using WeakReference to avoid tight coupling with the objects using them. When we store the delegate that will be executed by the Messenger or respectively the RelayCommand, we store them as WeakAction instances. This causes the delegate to be “dehydrated” and stored as a MethodInfo. When we “rehydrate” the delegate, we notice that the closure has been lost, and the call fails. I am experimenting with ways to work around that limitation (i.e storing the delegates are actual Action or Func and not dehydrating them, which will of course cause a strong coupling to occur… but would be acceptable in some cases if the developer explicitly opts into this). For the moment, closures are not supported and the developer needs to find another way, for example storing the parameter in an attribute or a list of some kind.

ViewModelBase

I optimized the code a bit there and made it less redundant. I also made the RaisePropertyChanged methods public (was: protected) following a user’s request. This can make sense in certain scenarios when an external object wants to call this method on another VM.

NavigationService

Here too I fixed some bugs. I also added new features for iOS:

  • Navigating with an unconfigured key in iOS: In iOS, the key passed to the NavigateTo method is often the same value as the corresponding Storyboard ID set in the Storyboard designer for a given controller. Until V5.3, you had to configure the key for the NavigationService, which was often leading to code such as
    Nav.Configure(“SecondPage”, “SecondPage”);
    this didn’t quite make sense. As of V5.3, if you call NavigateTo with a key that is not configured, we will attempt to find a corresponding controller with this same Storyboard ID. Of course if you want to use a different ID, you can still configure the navigation service like before.
  • Retrieving parameter without deriving from ControllerBase: Until now, the implementation used to retrieve a navigation parameter from the NavigationService forced you to derive your controller from ControllerBase. That was annoying, especially in cases where you had to derive from another base class anyway. I removed this restriction. Instead, you can now retrieve the NavigationService from the ServiceLocator in the ViewDidLoad method, and then call the GetAndRemoveParameter method to get the navigation parameter (if there is one). This is the same method than in the Android NavigationService.

Binding system

I fixed a few bugs here which were causing the data binding to fail in certain scenarios. I also added a lot of unit tests to test current and new features (currently about 300 unit tests which run in both iOS and Android), as well as a few features. Expect samples very soon!

  • FallbackValue: This value can be set in the SetBinding method (or in the Binding constructor) and will be used in case an error occurs when the Binding is being resolved. This can happen, for example, if you have a complex path expression and one of the elements is null, which would cause a NullReferenceException to happen inside the Binding. This exception is caught and nothing happens in the application, but the FallbackValue will be used as the Binding value if the user has set it. This can be used for information purposes. For example, if your source property is MyViewModel.SelectedItem.Name, and nothing is selected, the SelectedItem is null and the FallbackValue (for instance “Nothing selected yet”) is used.
  • TargetNullValue: This value can also be set in the SetBinding method (or in the Binding constructor) and will be used in case the Binding value is null. This can also be used for information purposes.
  • SetCommand with static parameter: I added an overload to the SetCommand extension method which can be used to pass a static parameter to the ICommand’s Execute and CanExecute methods. Prior to V5.3, you had to define a binding for this (and use the SetCommand(…, Binding) method) which was very cumbersome in case the binding value never changed. Now you can use the SetCommand method with a simple value (or if you want to observe the value you can still use the SetCommand method with a binding).
  • SetCommand for ICommand: In previous versions, you could only use SetCommand with a RelayCommand (or RelayCommand<T>), which was an oversight. Now I modified this method to work with any ICommand.
  • New name for UpdateSourceTrigger: This method is now named ObserveSourceEvent. The old method is still available but marked as deprecated. The old name was confusing for users.
  • New name for UpdateTargetTrigger: Similarly, this method is now named ObserveTargetEvent. The old method is still available but marked as deprecated.
  • Binding with implicit event names: When you set a binding on a UI element in Android and iOS, you must also specify which event should be observed for changes. This is necessary because properties in these elements, unlike in Windows, aren’t depedency properties. For instance, you can choose between FocusChange or TextChanged for an EditText, etc. In the huge majority of cases however, the same event is used over and over for a given element.
    On Android, the TextChanged event is used for an EditText and the CheckedChange event for CheckBox; on iOS, the ValueChanged event is used for UISwitch, the Changed event for UITextView, and the EditingChanged for UITextField. Note that existing code does not need to be changed unless of course you want to simplify it. And like before, you can continue to use ObserveSourceEvent and ObserveTargetEvent (formerly UpdateSourceTrigger and UpdateTargetTrigger) to specify a different event if needed.
  • SetCommand with implicit event names: Like with the Binding class, when we set a Command on a control, we specify which event must be observed to trigger the command. For commonly used controls, this is mostly the same event. To simplify the code, you don’t have to explicitly specify these events anymore. The events that are observed implicitly are: On Android the Click event for Button, and the CheckedChange event for CheckBox. On iOS, the TouchUpInside event for UIButton, the Clicked event for UIBarButtonItem and the ValueChanged event for UISwitch. Of course you can also continue to specify these events explicitly, or any other event you wish to observe instead.
  • Binding to private fields and local variables: In previous versions, you could only set a binding on public properties (for example public MainViewModel Vm, or public CheckBox MyCheck; in V5.3, you can also set bindings on objects which are saved as private attributes. You can even create a new Binding (using the Binding constructor instead of the SetBinding method) on elements which are defined as local variables.
  • Binding on RecyclerView, TableViewSource and CollectionViewSource cells: The feature above (binding on local variables) can be useful, for example to create a new binding between a data item and the cell that represents it in a list control. I’ll have blog posts for RecyclerView, TableViewSource and CollectionViewSource.

As you can see, this is a massive change set and I am really happy that your excellent feedback has led to these improvements. Of course the task is not over and there is more coming. V5.3 should greatly improve working with data binding in MVVM Light, in Xamarin.iOS and Xamarin.Android. As always, keep your feedback coming!

For more information about data binding in Xamarin.iOS and Xamarin.Android, you can watch my Xamarin Evolve 2016 session (slides, sample code and video recording will be posted ASAP).

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Slides and Samples for my talk at TechDays Switzerland

.NET, Phone, TechDays, Technical stuff, Universal Windows Platform UWP, Windows 10, XAML
No Comments

On Tuesday, I had the pleasure to talk to an almost full movie theater room about Windows 10 and the Universal Windows Platform UWP. I think the talk went well, and I had a lot of positive feedback later. 50 minutes sure is short for a talk, but on the plus side it forces you to concentrate on the essential. I really loved finishing my talk with a demo on the Windows Continuum, and even presenting the last few slides from my trusted Lumia 950XL directly on the big movie screen.

To all the participants, I extend a big thank you for the welcome. Unfortunately the session was not recorded, but I am sure I will have other occasions to show this material!

As promised I posted the slides, sample code as well as a small video I made. This video shows the Windows Islandwood (iOS) Bridge sample application running in the iOS simulator. In the sample code, you will find the iOS project after conversion to Windows 10. Finally make sure to check the slides for various resource links.

Happy coding!
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook
 

Enabling / Disabling design data in Visual Studio 2015 Update 1

.NET, Blend, MVVM, Technical stuff, Universal Windows Platform UWP, Visual Studio, Work, XAML
No Comments

If like me you use design time data in Blend or the Visual Studio designer, you may have noticed a small change that is actually very convenient, but maybe not the most discoverable feature ever: You can now switch design time data on or off very easily!

To illustrate this, follow the steps:

  • Start Visual Studio 2015 Update 1.
  • (if you have not done so already) Install MVVM Light with: Tools / Extensions and Updates / Online –> Search for mvvm light and install the extension.
  • After restarting Visual Studio, select File / New Project and create a new MvvmLight (Win10Univ) application. This will create a new Windows 10 Universal project with all the MVVM Light scaffolding.
  • Open MainPage.xaml in the Visual Studio designer (or select Design in Blend from the context menu on MainPage.xaml).
  • Make sure that you set the configuration manager to x86 (not ARM or x64).
  • Build the application.

At this point, you will see one of two images below:

2016-02-29_14-10-21

Figure 1: Design data is enabled

 2016-02-29_14-10-48

Figure 2: Design data is disabled

What’s the difference?

If you study both figures closely, you will see the difference at the bottom: Figure 1 shows actual data created in the code of the MVVM Light application (“Welcome to MVVM Light [design]” and the “Starting…” label for the Clock), while figure 2 shows the names of the databound properties (WelcomeTitle and Clock) instead. Switching from one figure to the other is done by using a new button on the design surface, which is a little hard to find. Here is an illustration:

2016-02-29_14-16-09

This small button is tooltipped “Enable Project Code”.

What this button does is enable or disable a feature that MVVM Light applications are taking advantage of: The possibility to run some of your app code while the application is loaded in the visual designer. If the button is toggled on, the design time code will be enabled, which explains why the WelcomeTitle label shows the design time text, and the Clock shows the initialization text. This is useful, because it will allow you to design your app visually without having to actually run it, and so you will be faster.

On the other hand however, design time code can crash the visual designer. This type of errors can be fixed by updating the design time data, but they are time consuming, and sometimes it is just not worth it. In those cases, you may want to disable the design time code for the current view, which can be done by toggling the small button off.

In the case where the button is disabled, you can still edit the UI somehow, because the name of the property will be shown, and you can at least set the font, font size, foreground color  etc, which is better than nothing. For lists, this works too: If the design time code is enabled, the design time elements will be shown like in figure 3. On the other hand, if you disable the design time code, three “dummy” items will be created, which allows you to edit the item template visually. Here is an example taken from an app I am currently working on.

 2016-02-29_17-30-17

In addition, it also enables some level of design work with configurations that were not initially supported by the visual designer: ARM and x64. You can verify this by changing the configuration in the MVVM Light application above. Here the toggle button becomes disabled, and the view in figure 2 is displayed.

Having the possibility to disable design time code renders the visual designer more stable by allowing the user to eliminate possible design time error from the equation, and to still use the designer even if the design time code fails. It also allows some level of designer usage even with ARM or x64 configurations. This should accelerate things especially towards the end of the project, when maintaining the design time data can be time consuming.

Happy coding
Laurent

GalaSoft Laurent Bugnion
Laurent Bugnion (GalaSoft)
Share on Facebook