Tag Archive : XAML

/ XAML

Sometimes we need to show a custom value in our XAML and this operation is not always immediate but with this tutorial you’ll discover how easy it is.

Let’s say that in our photo app we have a setting for the size of our photo. We store this setting as an integer but of course we want to show a better information to the user. Let’s say that

  • 0: Small
  • 1:Medium
  • 2: Large
  • 3: Full Size

This is what we want to achieve (Image Size):

A first idea could be to add a label with a simple text and to change the text from the code behind. Something like this:

<Label  Text="{Binding MyText}"/>

But we are better developers than that so we want to use an integer and a Converter:


<Label  Text="{Binding ImageSize, StringFormat='Image Size ({0})', Converter={StaticResource IntToImageSizeConverter}}"/>

As you have seen, instead of using a text, here we use our integer value, a converter and a StringFormat to format our text.

In our converter we receive an integer value and we return an element of the PhotoSize enum. This is the source code of the converter:

IValueConverter implementation public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is int b)
            {
                switch (b)
                {
                    case 0: return PhotoSize.Small;
                    case 1: return PhotoSize.Medium;
                    case 2: return PhotoSize.Large;
                    case 3: return PhotoSize.Full;
                }
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

The latest thing to do is to register the converter in our dictionary:

<helpers:IntToImageSizeConverter x:Key="IntToImageSizeConverter"/>

With this code we can use our integer variable to show a more meaningful text. Easy. Isn’t it?

If you want to know more or you need more info, write a comment here. If you liked the article share it!

The MVVM and Fody

The MVVM (Model, View, ViewModel) pattern helps you to organise and structure your code to create better apps.With this pattern you can split your code in 3 main parts:Model: Where you put your dataViewModel: It’s the logic of your app and a link between the Model and the ViewView: It’s the UI of your app (usually written in XAML) The main idea is to keep model, logic and UI completely separated.  And let’s be honest, this is how you should write your app.The interaction between the View and the ViewModel is done with the Data Binding

The Data Binding

The Data Binding is the connection between the UI and ViewModel of your app.You use it to connect a control (eg. a text) of your UI to your logic.Let’s say that we have an Entry (where a user can insert a text) and we want to link it to our ViewModel.We have something like this:in our UI (the View):

<Entry Text="{Binding Username}" Placeholder="Your username" />

In our ViewModel:

//OUR PROPERTY
        private string _username;

        public string Username
        {
            get => _username;
            set
            {
                _username = value;
                OnPropertyChanged();
            }
        }

In this case we have linked the Entry in our UI with the property (Username) in our ViewModel. When the user writes something in this entry, the Username value will change accordingly. And because the link is bidirectional (by default but you can change this behaviour), if we change the property value (eg. loading it from a database) the UI will change accordingly. It’s amazing. Isn’t it?

How to improve the code

To make a link between the UI and the ViewModel we need to use properties. Inside the set of each property we must call OnPropertyChanged (so our ViewModel must implement the INotifyPropertyChanged interface).It works, that’s great, but in a View usually we have a lot of interactive controls and for each of these we should need a property so there are cases where in our ViewModel we have many properties and you can imagine that the code is not readable anymore.Can we improve this? YES!

FODY

Fody is a library for IL weaving (the process to manipulate/inject code in IL). To put it easy, Fody will update automatically our code for us adding new cool features. In this case we are interested in a particular nuget plugin for Fody called PropertyChanged. This plugin will “Inject code which raises the PropertyChanged event, into property setters of classes which implement INotifyPropertyChanged.”What it means, is that we don’t have to explicitly call OnPropertyChanged() but we can instead use Auto-Properties.We can therefore convert our previous Username property to this:

public string Username { get; set; }

We have reduced the number of lines of code from 10 to 1. IMPRESSIVE!. Let’s say that in our ViewModel we have 20 properties, we have 200 lines of code only to declare our properties. With Fody & PropertyChanged plugin we can have only 20 lines of code instead of 200, saving 180 lines! Not Bad!

How to add it to your project

The process in incredibly easy:

  1. In your project install the Fody plugin (only in your PCL/.Net Standard project, in case of Xamarin, you don’t need to install in the Android, iOS,UWP projects): Fody
  2. Install the PropertyChanged plugin (only in your PCL/.Net Standard project): PropertyChanged
  3. Add to your PCL/.NetStandard project a new file called FodyWeavers.xml
  4. Open the file and change its content to:
<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
    <PropertyChanged/>
</Weavers>

IMPORTANT: PropertyChanged will convert your properties only inside the viewmodels that implement the INotifyPropertyChanged interface. So don’t forget to do it in your ViewModels where you want to use Fody PropertyChanged:

public class LoginViewModel : INotifyPropertyChanged