In my demo .NET MAUI application I have this model:
public class Person
{
public string Name { get; set; }
public string Email { get; set; }
}
This is my ViewModel:
public class MainViewModel : BaseViewModel
{
private Person _selectedPerson;
public Person SelectedPerson
{
get => _selectedPerson;
set
{
if (_selectedPerson != value)
{
_selectedPerson = value;
OnPropertyChanged(nameof(SelectedPerson));
OnPropertyChanged(nameof(People));
}
}
}
public ObservableCollection<Person> People { get; } = new ObservableCollection<Person>
{
new Person { Name = "John Doe", Email = "john.doe@example.com" },
new Person { Name = "Jane Doe", Email = "jane.doe@example.com" },
new Person { Name = "Bob Smith", Email = "bob.smith@example.com" },
new Person { Name = "Alice Johnson", Email = "alice.johnson@example.com" },
};
public ICommand SelectPersonCommand => new Command<Person>(person =>
{
SelectedPerson = person;
});
public MainViewModel()
{
}
}
I have the enumerable People bounded to my ListView:
<ContentPage
x:Class="MAUIPlayground.MainPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converters="clr-namespace:MAUIPlayground.Converters"
x:Name="mainPage">
<ContentPage.Resources>
<ResourceDictionary>
<converters:SelectedItemToBooleanConverter x:Key="SelectedItemToBooleanConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout>
<ListView ItemsSource="{Binding People}" SelectedItem="{Binding SelectedPerson}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<CheckBox IsChecked="{Binding ., Converter={StaticResource SelectedItemToBooleanConverter}, ConverterParameter={Binding Source={x:Reference mainPage}, Path=BindingContext.SelectedPerson}}" />
<Label Text="{Binding Name}" />
<Label Text="{Binding Email}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
And this is my SelectedItemToBooleanConverter:
public class SelectedItemToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
var person = (Person)value;
var selectedPerson = (Person)parameter;
return person == selectedPerson;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
From what I understand I should be able to parse both value and parameter arguments on the converter to People. This is true for value, however parameter is passed as Microsoft.Maui.Controls.Binding when I'm trying to pass Person as argument. How can I achieve this?