Reputation: 160
Have a small app that I would like to capture information from my code behind and pass it to my ViewModel. The ViewModel has access to a 3rd Party API, so I would send that data too. I don't know the best way to pass that type of information. MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:vm="clr-namespace:BlueRC.ViewModels"
x:Class="BlueRC.Views.MainPage"
x:DataType="vm:MainViewModel">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="10*" />
<RowDefinition Height="90*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Grid.Column="0"
Text="Connect to Bluetooth"
FontAttributes="Bold"
HorizontalOptions="CenterAndExpand"
Command="{Binding BluetoothConnectClickCommand}"/>
<Label Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2"
Text="{Binding ConsoleMessage}"
x:Name="StatusMessage"/>
<BoxView
Grid.ColumnSpan="3" Grid.Row="1"
VerticalOptions="Center"
HorizontalOptions="Center"
Color="Gray">
<BoxView.GestureRecognizers>
<PanGestureRecognizer PanUpdated="PanGestureRecognizer_PanUpdated" />
</BoxView.GestureRecognizers>
</BoxView>
</Grid>
</ContentPage>
Code behind MainPage.xaml.cs
namespace BlueRC.Views;
public partial class MainPage : ContentPage
{
private double deltaX;
private double deltaY;
public MainPage(MainViewModel viewModel)
{
InitializeComponent();
BindingContext = viewModel;
}
private void PanGestureRecognizer_PanUpdated(object sender, PanUpdatedEventArgs e)
{
deltaX = e.TotalX; // want to send deltaX to my ViewModel
deltaY = e.TotalY; // want to send deltaY to my ViewModel
if (e.StatusType == GestureStatus.Completed || e.StatusType == GestureStatus.Canceled)
{
// Capture the deltas and send the info over. Then reset them.
deltaX = 0f;
deltaY = 0f;
}
StatusMessage.Text = $"X: {deltaX:N}, Y: {deltaY:N} StatusType: {e.StatusType}";
}
How can I send deltaX and deltaY to my ViewModel? If it was a matter of creating a RelayCommand and linking it I would have done that ages ago. PanGestureRecognizer doesn't contain the Command attribute for me to data bind to.
Any advice?
Upvotes: 0
Views: 4773
Reputation: 21243
Getting hold of ViewModel.
Two Possibilities:
public MyView(MyViewModel vm)
{
InitializeComponent();
VM = vm;
BindingContext = vm;
}
private MyViewModel VM;
private MyViewModel VM => BindingContext as MyViewModel;
Either way, to access:
VM.SomeProperty = ...;
Upvotes: 3