Net maui converter is not working ?

Sami 881 Reputation points
2023-05-31T00:33:02.1966667+00:00

Converter is not working as expected ? Command on Button is working, I have checked Also <cb:FavoriteButton /> button is in collectionview.

public class BoolToObjectConverter<T> : IValueConverter
{
    public T TrueObject { get; set; }
    public T FalseObject { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool)value ? TrueObject : FalseObject;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((T)value).Equals(TrueObject);
    }
}


 
 <cb:FavoriteButton x:Name="favButton" BindingContext="{x:Static local:AppLocator.DetailViewModel}"    FavoriteCommand="{Binding FavoriteAddCommand}">
                                <cb:FavoriteButton.FavoriteTextColor>
                                    <Binding Source="{x:Reference favButton}"
                             Path="IsFavoriteAdd">
                                        <Binding.Converter>
                                            <conv:BoolToObjectConverter x:TypeArguments="Color"
                                                         TrueObject="{StaticResource Orange}"
                                                         FalseObject="{StaticResource Gray}" />
                                        </Binding.Converter>
                                    </Binding>
                                </cb:FavoriteButton.FavoriteTextColor>
                            </cb:FavoriteButton>

                          
                         
                          
                                     
                                  

                                                   
                                                     
                                       
                               
                              
                        
                         
                                  
                 
                                  
                                      
                 
                            
                                 
                   
                          
                                            
                                                     
                                               
                             
                       
 
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,190 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 71,836 Reputation points Microsoft Vendor
    2023-06-01T07:26:43.6+00:00

    Hello,

    Command on Button is working, I have checked Also <cb:FavoriteButton /> button is in collectionview.

    Do you need every item to have IsFavoriteAdd state separately in the collectionview?

    If so, firstly, we need to remove IsFavoriteAdd property to your Model. Here is my tested Model.

    
    public class MyModel: INotifyPropertyChanged
    {
        public string  name { get; set; }
        public bool _IsFavoriteAdd = false;
        public bool IsFavoriteAdd
        {
            get
            {
                return _IsFavoriteAdd;
            }
            set
            {
                _IsFavoriteAdd = value;
                OnPropertyChanged("IsFavoriteAdd");
            }
        }
       protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
    

    I do not know what is mean about BindingContext="{x:Static local:AppLocator.DetailViewModel}", I moved it.

    Here is my layout.

    • I add CurrentMyModel property in the FavoriteButton, it could transfer current model to the viewmodel's FavoriteAddCommand. Then we can control the item's IsFavoriteAdd state separately
    • I removed Source="{x:Reference favButton}", because you can get the current model directly and I add reference for the command like FavoriteCommand="{Binding FavoriteAddCommand , Source={x:Reference this}}". x:Name="this" added to the ContentPage
     
    <?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:cb="clr-namespace:MauiConvertDemo"
                 xmlns:conv="clr-namespace:MauiConvertDemo"
                 x:Name="this"
                 x:Class="MauiConvertDemo.MainPage">
        <ScrollView>
            <VerticalStackLayout > 
            <CollectionView  ItemsSource="{Binding Items}">
                    <CollectionView.ItemTemplate>
                        <DataTemplate>
                            <StackLayout>
                                <cb:FavoriteButton x:Name="favButton" FavoriteCommand="{Binding FavoriteAddCommand , Source={x:Reference this}}" CurrentMyModel="{Binding  Path=.}" >
                                    <cb:FavoriteButton.FavoriteTextColor>
                                        <Binding
                                         Path="IsFavoriteAdd">
                                            <Binding.Converter>
                                                <conv:BoolToObjectConverter x:TypeArguments="Color"
                                                              TrueObject="{StaticResource Orange}"
                                                             FalseObject="{StaticResource Gray}" />
                                            </Binding.Converter>
                                        </Binding>
                                    </cb:FavoriteButton.FavoriteTextColor>
                                </cb:FavoriteButton>
                            </StackLayout>
                        </DataTemplate>
                    </CollectionView.ItemTemplate>
                </CollectionView>
            </VerticalStackLayout>
        </ScrollView>
    </ContentPage>
    

    Here is my layout's background code. I added viewmodel's content directly for testing.

    public partial class MainPage : ContentPage
    {
        public ICommand FavoriteAddCommand { get; set; }
        public ObservableCollection<MyModel> Items { get; set; }
        public MainPage()
        {
            InitializeComponent();
            Items = new ObservableCollection<MyModel>();
            for (int i = 0; i < 10; i++)
            {
                Items.Add(new MyModel() {name= i.ToString() });
            }
            FavoriteAddCommand = new Command<object>(FavItem);
            BindingContext = this;
        }
        private void FavItem(object obj)
        {
            MyModel myModel = obj as MyModel;
            myModel.IsFavoriteAdd = true ? !myModel.IsFavoriteAdd : myModel.IsFavoriteAdd;
       }
    }
    

    In the end, please open your FavoriteButton's background code, Add CurrentMyModel bindableProperty.

     public static BindableProperty CurrentMyModelProperty =
                BindableProperty.Create(nameof(CurrentMyModel), typeof(object), typeof(FavoriteButton),defaultBindingMode:BindingMode.TwoWay);
    
       public object CurrentMyModel
        {
            get => (object)GetValue(CurrentMyModelProperty);
            set => SetValue(CurrentMyModelProperty, value);
        }
    

    Open your FavoriteButton's layout code. Add binding source for CommandParameter

                    <Button x:Name="btnFavorite"  Text="{StaticResource icon-star}" Style="{StaticResource fontelloButton}" TextColor="{Binding Source={x:Reference FavoriteView}, Path=FavoriteTextColor, Mode=OneWay}"  VerticalOptions="Center" Command="{Binding Source={x:Reference FavoriteView}, Path=FavoriteCommand, Mode=TwoWay}" />
    
    
    <Button x:Name="btnFavorite"  Text="{StaticResource icon-star}"
    Style="{StaticResource fontelloButton}"
                        TextColor="{Binding Source={x:Reference FavoriteView}, Path=FavoriteTextColor, Mode=OneWay}"
                        VerticalOptions="Center"
    
                        CommandParameter="{Binding Source={x:Reference FavoriteView}, Path=CurrentMyModel, Mode=TwoWay}"
    
                        Command="{Binding Source={x:Reference FavoriteView}, Path=FavoriteCommand, Mode=TwoWay}" />
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.