I'm learning .NET MAUI and I'm making an internet radio application. I'm using the MediaElement control from the CommunityToolkit package and that control has methods like Play()
or Stop()
in it and I'd like to use them in my ViewModel. They are so far only available from Code-behind after setting x:Name
in XAML. And I would like to use these methods, but in my ViewModel specifically. How could I rewrite the code so that it preserves the MVVM structure?
NowPlayingViewModel.cs
namespace Rad.io.Client.MAUI.ViewModels
{
[QueryProperty(nameof(CurrentStation), "CurrentStation")]
public class NowPlayingViewModel : INotifyPropertyChanged
{
...
public StationInfo CurrentStation
{
get => currentStation;
set
{
currentStation = value;
RaisePropertyChanged();
}
}
public NowPlayingViewModel(IRadioBrowserClient radioBrowserClient)
{
this.radioBrowserClient = radioBrowserClient;
}
public ICommand OnStopPressed => new Command(() => {
mediaElement.Stop(); // <- How to call method Stop() available in MediaElement control?
});
public ICommand OnPlay => new Command(() =>
{
mediaElement.Play(); // <- How to call method Play() available in MediaElement control?
});
...
}
}
NowPlayingView.xaml.cs
namespace Rad.io.Client.MAUI.Views;
public partial class NowPlayingPanel : ContentView
{
public NowPlayingPanel()
{
InitializeComponent();
}
void playStopButton_Clicked(System.Object sender, System.EventArgs e)
{
if (mediaElement.CurrentState == CommunityToolkit.Maui.Core.Primitives.MediaElementState.Playing)
{
mediaElement.Pause();
} else if (mediaElement.CurrentState == CommunityToolkit.Maui.Core.Primitives.MediaElementState.Paused)
{
mediaElement.Play();
}
}
}
NowPlayingView.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewmodel="clr-namespace:Rad.io.Client.MAUI.ViewModels"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
x:DataType="viewmodel:NowPlayingViewModel"
x:Class="Rad.io.Client.MAUI.Views.NowPlayingPanel">
...
<toolkit:MediaElement x:Name="mediaElement" Grid.Column="1"
ShouldShowPlaybackControls="False"
BackgroundColor="DarkCyan"
ShouldAutoPlay="True"
Source="{Binding CurrentStation.Url}"/>
...
<Button x:Name="playStopButton" Text="Play/Stop" Clicked="playStopButton_Clicked"/>
</HorizontalStackLayout>
</FlexLayout>
</Grid>