Hi paramjit-0569,
Welcome to our Microsoft Q&A platform!
According to document: Xamarin Community Toolkit C# Markup, we can bind the command as followed.
new Button{Text="English"}.Row (0) .Column (0)
.Bind(BackgroundColorProperty,nameof(vm.SelectedLanguage),BindingMode.TwoWay,converter:stringToColorConverter)
.BindCommand (nameof(vm.TapCommand), vm, nameof(vm.SelectedLanguage)),
Here is the full code demo you can refer to.
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
MainPageViewModel vm = new MainPageViewModel();
this.BindingContext = vm;
FuncConverter<string, Color> stringToColorConverter = new FuncConverter<string, Color>(language => language == "English" ? Color.Blue : Color.Gray);
Content = new Grid
{
Children =
{
new Button{Text="English"}.Row (0) .Column (0)
.Bind(BackgroundColorProperty,nameof(vm.SelectedLanguage),BindingMode.TwoWay,converter:stringToColorConverter)
.BindCommand (nameof(vm.TapCommand), vm, nameof(vm.SelectedLanguage)),
new Button{Text="हिंदी"} .Row (1) .Column (0)
.Bind(Button.BackgroundColorProperty,nameof(vm.SelectedLanguage),BindingMode.TwoWay,converter:stringToColorConverter)
.BindCommand(nameof(vm.TapCommand), vm, nameof(vm.SelectedLanguage))
}
};
}
}
MainPageViewModel.cs
class MainPageViewModel : INotifyPropertyChanged
{
public ICommand TapCommand { get; private set; }
string selectedLanguage;
public string SelectedLanguage
{
get => selectedLanguage;
set
{
if (selectedLanguage == value || value == null)
return;
selectedLanguage = value;
OnPropertyChanged("SelectedLanguage");
}
}
public MainPageViewModel()
{
SelectedLanguage = "English";
TapCommand = new Command<object>(Tap);
}
void Tap(object obj)
{
Debug.WriteLine("Tap");
// get parameter
Debug.WriteLine(obj.ToString());
SelectedLanguage = SelectedLanguage == "English" ? "हिंदी" : "English";
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Regards,
Kyle
If the response is helpful, please click "Accept Answer" and upvote it.
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.