I need to pass a SearchBar Text as a parameter to the ViewModel but I don't know how to do that. The only way I could was getting the text in the Code-Behind and sending it to ViewModel by parameter
Shop.xml
SearchCommand="{Binding PesquisarButton}" SearchCommandParameter="{Binding .}" TextChanged="TextoMudou"
<SearchBar x:Name="searchBar" Grid.Column="0" Grid.Row="1" Margin="-5,10,0,10" BackgroundColor="Transparent" SearchCommand="{Binding PesquisarButton}" SearchCommandParameter="{Binding .}" TextChanged="TextoMudou" />
Shop.cs
here I take the text and send it as a parameter to the ViewModel , but I believe it's a bad way
private void TextoMudou(object sender, EventArgs args)
{
palavra = ((SearchBar)sender).Text;
BindingContext = new ViewModel.ShopViewModel(palavra);
}
ShopViewModel.cs
I created a 'Text' variable where to store the word that came by parameter and use it in the command
public string Texto { get; set; }
Constructor
public ShopViewModel(string palavra="")
{
this.Texto = palavra;
}
Command
Here I use the text variable I created, but I wanted this command to receive the parameter
public ICommand btnBuscar => new Command(() =>
{
var ListaFiltrada2 = ListaRoupas.Where((item)=> item.Nome.Contains(Texto)).ToList();
Preencher(ListaFiltrada2);
});
what I want is for the SearchBar Text to come straight to the Command in the viewmodel, is there any way? Github: https://github.com/IagoAntunes/FashionShop/tree/master/LojaRoupas/LojaRoupas
CodePudding user response:
You can send any object in the command like this:
public Command<object> btnBuscar { get; set; }
public ViewModel() // Constructor
{
btnBuscar = new Command<object>(btnBuscarFunction);
}
private void btnBuscarFunction (object obj){
//Parse obj to any Type you want
string Texto = (string)obj;
var ListaFiltrada2 = ListaRoupas.Where((item)=> item.Nome.Contains(Texto)).ToList();
Preencher(ListaFiltrada2);
}
CodePudding user response:
You can pass your command to receive a function that handle the process. For example:
Your XAML:
<Button Text="OK"
BackgroundColor="#228B22"
BorderRadius="10"
Command="{Binding SaveCommand}"/>
Then in your ViewModel (using async as a best practice):
private Command _SaveCommand;
public Command SaveCommand => _SaveCommand ??= new Command(async () => await SaveCommandExecAsync(string texto));
private async Task SaveCommandExecAsync(string texto)
{
string text = texto;
var ListaFiltrada2 = ListaRoupas.Where((item)=> item.Nome.Contains(text)).ToList();
Preencher(ListaFiltrada2);
}
