4 New Features You Must Try in Xamarin.Forms 4.5
Tags: xamarin, android, ios, csharp
Published: 2020-03-18 13:07:47

---
title: 4 New Features You Must Try in Xamarin.Forms 4.5
published: true
date: 2020-03-16 12:00:21 UTC
tags: xamarin, android, ios, csharp
canonical_url: https://www.syncfusion.com/blogs/post/4-new-features-you-must-try-in-xamarin-forms-4-5.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/ojcfu9dv6asfb2upnuzx.png
---

In each new release, Xamarin always has some exciting new features for us. The Xamarin.Forms 4.5 release, too, contains a lot of improvements and some exciting new features.

In this blog post, I will take you through the features of Xamarin.Forms 4.5 that excited me. I recommend that you try these features:

- MediaElement (preview)
- VSM TargetName
- The stable release of AndroidX
- State triggers (Preview)

## MediaElement (preview)

A long waits is over with the availability of the new [MediaElement](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/mediaelement) control. Finally, Xamarin.Forms introduces [MediaElement](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/mediaelement), a video and audio player interface used to play media.

The various sources supported by the MediaElement include the web, using a URI (HTTP or HTTPS); a resource embedded in the platform application, using the ms-appx:/// URI scheme; files that come from the app’s local and temporary data folders, using the ms-appdata:/// URI scheme; and the device’s library.

Its feature set includes [aspect](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.mediaelement.aspect#Xamarin_Forms_MediaElement_Aspect), [auto play](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.mediaelement.autoplay#Xamarin_Forms_MediaElement_AutoPlay), [buffering progress](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.mediaelement.bufferingprogress#Xamarin_Forms_MediaElement_BufferingProgress), [duration](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.mediaelement.duration#Xamarin_Forms_MediaElement_Duration), [looping](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.mediaelement.islooping#Xamarin_Forms_MediaElement_IsLooping), [keep screen on](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.mediaelement.keepscreenon#Xamarin_Forms_MediaElement_KeepScreenOn), [position](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.mediaelement.position#Xamarin_Forms_MediaElement_Position), and  [volume](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.mediaelement.volume#Xamarin_Forms_MediaElement_Volume). All these features are really amazing. Using these features, I just created my custom player with these options: video position, full screen, looping, play/pause, stop, and volume adjustment.

Let me describe the APIs I used to create these options in detail.

**View:** I used MediaElement, Button, and Slider to create my player UI.

```xml
<Grid>
  <Grid.ColumnDefinitions>
       <ColumnDefinition Width="*"/> <ColumnDefinition Width="50"/>
  </Grid.ColumnDefinitions>
      <MediaElement x:Name="videoPlayer" Aspect="AspectFit" Source="ms-appx:///Assets/BestXamarinUIControlswithIncrediblePerformance.mp4" ShowsPlaybackControls="False"/>
      <Slider x:Name="videoProgressSlider" VerticalOptions="End" Minimum="0" Maximum="100" ValueChanged="videoProgressSlider_ValueChanged"/>
      <Grid Grid.Column="1" >
       <Grid.RowDefinitions>
          <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/>
       </Grid.RowDefinitions>
      <Button Grid.Row="0" BackgroundColor="White" FontFamily="SEGMDL2.TTF#Segoe MDL2 Assets" Text="" Clicked="Button_Clicked"/>
      <Button Grid.Row="1" BackgroundColor="White" Text="" FontFamily="SEGMDL2.TTF#Segoe MDL2 Assets" Clicked="Button_Clicked_1"/>
      <Button Grid.Row="2" BackgroundColor="White" Text="" FontFamily="SEGMDL2.TTF#Segoe MDL2 Assets" Clicked="Button_Clicked_2"/>
      <Button Grid.Row="3" BackgroundColor="White" Text="" FontFamily="SEGMDL2.TTF#Segoe MDL2 Assets" Clicked="Button_Clicked_3"/>
      <Button Grid.Row="4" BackgroundColor="White" Text=""  FontFamily="SEGMDL2.TTF#Segoe MDL2 Assets"  Clicked="Button_Clicked_4"/>
  </Grid>
</Grid>
```

**Video position:**   I used the [Position](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.mediaelement.position?view=xamarin-forms#Xamarin_Forms_MediaElement_Position) property of type TimeSpan to describe the current progress through the media’s playback time. As seen in the following code, I calculated the percentage value based on the current value of the slider.

```csharp
private void videoProgressSlider_ValueChanged(object sender, ValueChangedEventArgs e)
{
   var duration = this.videoPlayer.Duration.Value.Ticks;
   var slideValue = (sender as Slider).Value;
   var durationPercentage = duration / 100;
   var tickValue = durationPercentage * slideValue;
   var timeSpan = new TimeSpan((long) tickValue);
   this.videoPlayer.Position = timeSpan;
}
```

**Full screen:** The [Aspect](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.mediaelement.aspect#Xamarin_Forms_MediaElement_Aspect) property of MediaElement of type [Aspect](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.aspect) determines how the media will be scaled to fit the display area. You can make the video fill the screen using this option.

```csharp
this.videoPlayer.Aspect = Aspect.Fill;
```

**Play/pause and stop:** MediaElement has built-in methods for these: Play(), Pause() and Stop().

**Volume:** Using the API [Volume](https://docs.microsoft.com/en-us/dotnet/api/xamarin.forms.mediaelement.volume#Xamarin_Forms_MediaElement_Volume) of type double, the media’s volume can be adjusted. The volume is represented on a linear scale between 0 and 1.

```csharp
this.videoPlayer.Volume = 0.5;
```
# ![](https://www.syncfusion.com/blogs/wp-content/uploads/2020/02/mediaelement.gif)

## VSM TargetName saves you from repeating code

In a classic approach to updating a property of a control based on its state, we may look for direct properties to set values in different states, or we could watch for a change in the state of the control to update it in the code-behind. VisualStateManager (VSM) makes it easier for developers to specify the appearance of a control depending on its visual state.

Now, VisualStateManager can target elements (in the visual tree) to set properties on any control within the same visual tree. This will help set the state on multiple controls. For example, I have a reset password page that contains a DataGrid with two Entries and a Button with the strength indicator views weak, medium, and strong. In a classical approach, I need to write a lot of code to set the state for each view. But now, with Xamarin.Forms 4.5, this is made simpler by setting the target element in a single element state.

```xml
<Grid x:Name="MainGrid" WidthRequest="200" HeightRequest="250" Padding="10" VerticalOptions="Center" HorizontalOptions="Center">
<StackLayout VerticalOptions="Center" Orientation="Vertical">
    <Entry  Placeholder="Current Password" IsPassword="True"/>
    <Frame x:Name="PasswordBorder" Padding="2" CornerRadius="0">
        <Entry Placeholder="New Password" TextChanged="PasswordEntry_TextChanged" IsPassword="True" >
            <VisualStateManager.VisualStateGroups>
                <VisualStateGroup Name="PasswordStrength">
                    <VisualState Name="WeakPassword">
                        <VisualState.Setters>
                            <Setter TargetName="PasswordBorder"  Property="Frame.BorderColor" Value="#ad1400"/>
                            <Setter TargetName="WeakGrid" Property="Grid.BackgroundColor" Value="#ffb4ab"/>
                            <Setter TargetName="MediumGrid" Property="Grid.BackgroundColor" Value="#00ffffff"/>
                            <Setter TargetName="StrongGrid" Property="Grid.BackgroundColor" Value="#00ffffff"/>
                            <Setter TargetName="StrengthLabel" Property="Label.Text" Value="Weak"/>
                        </VisualState.Setters>
                    </VisualState>
                    <VisualState Name="MediumPassword">
                        <VisualState.Setters>
                            <Setter TargetName="PasswordBorder"  Property="Frame.BorderColor" Value="#ad8a00"/>
                            <Setter TargetName="WeakGrid" Property="Grid.BackgroundColor" Value="#fcff9e"/>
                            <Setter TargetName="MediumGrid" Property="Grid.BackgroundColor" Value="#fcff9e"/>
                            <Setter TargetName="StrongGrid" Property="Grid.BackgroundColor" Value="#00ffffff"/>
                            <Setter TargetName="StrengthLabel" Property="Label.Text" Value="Medium"/>
                        </VisualState.Setters>
                    </VisualState>
                    <VisualState Name="StrongPassword">
                        <VisualState.Setters>
                            <Setter TargetName="PasswordBorder"  Property="Frame.BorderColor" Value="#02a60f"/>
                            <Setter TargetName="WeakGrid" Property="Grid.BackgroundColor" Value="#9effb8"/>
                            <Setter TargetName="MediumGrid" Property="Grid.BackgroundColor" Value="#9effb8"/>
                            <Setter TargetName="StrongGrid" Property="Grid.BackgroundColor" Value="#9effb8"/>
                            <Setter TargetName="StrengthLabel" Property="Label.Text" Value="Strong"/>
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
        </Entry>
    </Frame>
    <Grid>
        <Grid HeightRequest="20" ColumnSpacing="0" RowSpacing="0">
            <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions>
            <Grid x:Name="WeakGrid" Grid.Column="0" ColumnSpacing="0" RowSpacing="0"/>
            <Grid x:Name="MediumGrid" Grid.Column="1" ColumnSpacing="0" RowSpacing="0"/>
            <Grid x:Name="StrongGrid" Grid.Column="2" ColumnSpacing="0" RowSpacing="0"/>
        </Grid>
        <Label x:Name="StrengthLabel" VerticalOptions="Center" HorizontalOptions="Center" />
    </Grid>
    <Entry Placeholder="Confirm New Password" IsPassword="True"/>
    <Button Text="Reset Password" TextColor="White"/>
</StackLayout>
</Grid>
```
I set entry states “WeakPassword,” “MediumPassword,” and “StrongPassword” through Visual State Manager based on text length.

```csharp
private void PasswordEntry_TextChanged(object sender, TextChangedEventArgs e)
{
    var entryObject = sender as Entry;
    if (entryObject.Text.Length < 8)
    {
        VisualStateManager.GoToState(entryObject, "WeakPassword");
    }
    else if (entryObject.Text.Length < 12)
    {
        VisualStateManager.GoToState(entryObject, "MediumPassword");
    }
    else if (entryObject.Text.Length > 12)
    {
        VisualStateManager.GoToState(entryObject, "StrongPassword");
    }
}
```

![Example of VSM using TargetName](https://www.syncfusion.com/blogs/wp-content/uploads/2020/03/Example-of-VSM-using-TargetName.gif)<figcaption>Example of VSM using TargetName</figcaption>

## The stable release of AndroidX

[AndroidX](https://developer.android.com/jetpack/androidx/) packages fully replace the Support Library, so now the original Android Support Library is no longer maintained. Based on this update, Xamarin.Forms is also migrated to AndroidX from the original Android Support Library. So, it’s time to migrate your existing apps to AndroidX to make your app compatible with Android 10. Updating to AndroidX libraries makes it easier for developers to consume Android packages. Hopefully, it will provide several advantages in Xamarin.Forms and Xamarin.Essential in upcoming releases.

Are you planning to migrate your existing app? Then, this [blog](https://devblogs.microsoft.com/xamarin/androidx-nuget-packages-are-stable/) will be helpful for you.

## State triggers (preview)

Triggers allow you to change the appearance of controls based on events or property changes. Already, Xamarin.Forms has [property triggers](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/triggers#property-triggers), [data triggers](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/triggers#data-triggers), [event triggers](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/triggers#event-triggers), and [multi-triggers](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/triggers#multi-triggers). With  Xamarin.Forms 4.5, you can enjoy additional state triggers: [adaptive trigger](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/triggers#adaptive) , [compare state trigger](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/triggers#compare), [device state trigger](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/triggers#device) and [orientation trigger](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/triggers#orientation).

### Adaptive trigger

A VisualState change can be triggered when the window is specified with a height or width.

```xml
<VisualState x:Name="Vertical">
     <VisualState.StateTriggers>
          <AdaptiveTrigger MinWindowWidth="0" />
     </VisualState.StateTriggers>
     <VisualState.Setters>
          <Setter Property="Orientation"
          Value="Vertical" />
     </VisualState.Setters>
</VisualState>
```

### Compare state trigger

A VisualState change can be triggered when a property is equal to a specific value.

```xml
<VisualState x:Name="Checked">
     <VisualState.StateTriggers>
         <CompareStateTrigger Property="{Binding Source={x:Reference switch}, Path=IsToggled}"
                              Value="True" />
      </VisualState.StateTriggers>
      <VisualState.Setters>
        <Setter Property="BackgroundColor"
                Value="Blue" />
      </VisualState.Setters>
</VisualState>
```

### Device trigger

A VisualState change can be triggered based on the device platform on which the app is running.

```xml
<VisualState x:Name="iOS">
  <VisualState.StateTriggers>
     <DeviceStateTrigger Device="iOS" />
  </VisualState.StateTriggers>
  <VisualState.Setters>
     <Setter Property="BackgroundColor"
             Value="Orange" />
     </VisualState.Setters>
</VisualState>
```

### Orientation trigger

A VisualState change can be triggered when the orientation of the device changes.

```xml
<VisualState x:Name="Landscape">
     <VisualState.StateTriggers>
          <OrientationStateTrigger Orientation="Landscape" />
     </VisualState.StateTriggers>
     <VisualState.Setters>
     <Setter Property="BackgroundColor"
             Value="Orange" />
     </VisualState.Setters>
</VisualState>
```

## Other interesting features

The Xamarin.Forms 4.5 update is not limited to these exciting features. You can check out other interesting features and enhancement in Xamarin.Forms 4.5 in the [release notes](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/release-notes/4.5/4.5.0).

## Conclusion

I hope you, too, are excited about these new features available with Xamarin.Forms 4.5. So, why don’t you try them now? Start by downloading [Xamarin.Forms 4.5 in NuGet](https://www.nuget.org/packages/Xamarin.Forms/). Don’t forget to set flags for preview controls and to try our [Syncfusion Xamarin.Forms controls](https://www.syncfusion.com/xamarin-ui-controls), which are compatible with Xamarin.Forms 4.5. I am sure you will definitely enjoy this combo of Xamarin.Forms 4.5 and [Syncfusion Xamarin.Forms controls](https://www.syncfusion.com/xamarin-ui-controls)!

If you come across any issues using our controls with 4.5, please contact us through our [support forum](https://www.syncfusion.com/forums), [Direct-Trac](https://www.syncfusion.com/support/directtrac/), or [feedback portal](https://www.syncfusion.com/feedback/xamarin-forms). We are happy to assist you.

If you liked this blog post, we think you’ll also enjoy:

[Blog] [How to Use Xamarin.Forms Visual State Manager](https://dev.to/vijays/how-to-use-xamarin-forms-visual-state-manager-5785-temp-slug-6533184)

[Blog] [Easily Animate Your Xamarin Applications with Lottie Animations](https://dev.to/syncfusion/easily-animate-your-xamarin-applications-with-lottie-animation-26j5)

[Blog] [7 Ways to Boost Your Xamarin Development Productivity](https://dev.to/syncfusion/7-ways-to-boost-your-xamarin-development-productivity-2hoi)

[Ebook] [_Xamarin.Forms Succinctly_](https://www.syncfusion.com/ebooks/xamarin-forms-succinctly)

The post [4 New Features You Must Try in Xamarin.Forms 4.5](https://www.syncfusion.com/blogs/post/4-new-features-you-must-try-in-xamarin-forms-4-5.aspx) appeared first on [Syncfusion Blogs](https://www.syncfusion.com/blogs).