ARTICLE AD BOX
I am running into an issue trying to call a method in my ViewModel by using EventToCommand. When I use binding in the CommandParameter with a string, the method is called buy the passed parameter is null, even though it shows the value in a label with binding. When I use binding in the CommandParameter with an int, the method is not called.
I have tried changing the binding context and sending different parameters. If I send an unbound string, it passed the value of the string to the method.
My questions are why does the passed parameter show null in the method and why does the method not get called when using an int?
ViewModel:
using System.Collections.ObjectModel; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Crate_UI.Models; namespace Crate_UI.ViewModels; public partial class CrossingViewModel() : ObservableObject { public ObservableCollection<FactorUI> Factors { get; set; } = new(); public void SetMode(bool isSummaryMode) { Factors.Clear(); FactorUI factor = new(); factor.Id = 1; factor.AreaId = 123; factor.Name = "Name"; Factors.Add(factor); } [RelayCommand] public void BoundString(string pagename) { string Name = pagename; } [RelayCommand] public void BoundInt(int areaId) { int areaIndex = areaId; } }xaml page:
<?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" x:Class="Crate_UI.Views.CrossingPage" xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit" xmlns:views="clr-namespace:Crate_UI.Views" xmlns:viewmodels="clr-namespace:Crate_UI.ViewModels" xmlns:models="clr-namespace:Crate_UI.Models" x:DataType="viewmodels:CrossingViewModel" x:Name="CrossingPageXML" Shell.NavBarIsVisible="False"> <ContentPage.Resources> <DataTemplate x:Key="AreasDataTemplate" x:DataType="models:FactorUI"> <Grid RowDefinitions="Auto, Auto" ColumnDefinitions="Auto, Auto"> <CheckBox Grid.Row="0" Grid.Column="0"> <CheckBox.Behaviors> <toolkit:EventToCommandBehavior EventName="CheckedChanged" Command="{Binding BindingContext.BoundStringCommand, Source={x:Reference CrossingPageXML}}" CommandParameter="{Binding Name}" /> </CheckBox.Behaviors> </CheckBox> <Label Grid.Row="0" Grid.Column="1" Text="{Binding Name}" /> <CheckBox Grid.Row="1" Grid.Column="0"> <CheckBox.Behaviors> <toolkit:EventToCommandBehavior EventName="CheckedChanged" Command="{Binding BindingContext.BoundIntCommand, Source={x:Reference CrossingPageXML}}" CommandParameter="{Binding AreaId}" /> </CheckBox.Behaviors> </CheckBox> <Label Grid.Row="1" Grid.Column="1" Text="{Binding AreaId}" /> </Grid> </DataTemplate> </ContentPage.Resources> <CollectionView ItemsSource="{Binding Factors}" ItemTemplate="{StaticResource AreasDataTemplate}" /> </ContentPage>Model:
namespace Crate_UI.Models; public class FactorUI : IFactorUI { public int Id { get; set; } public int AreaId { get; set; } public string Name { get; set; } }