问题
So, this is my Model Class "Usuario"
This class has the Foreign key "IdTipoUsuario" that was declared in my database from SQL Server Management Studio. So I placed it here with the "IList" property:
namespace APPiGarbage.Models
{
public class Usuario
{
public int IdUsuario { get; set; }
public string Nome { get; set; }
public string Foto { get; set; }
public string Descricao { get; set; }
public string Email { get; set; }
public string Senha { get; set; }
public IList<TipoUsuario> TiposUsuarios { get; set; }
}
}
I have this other class TipoUsuario. This class has the "Nome" property that is supposed to be Binding in the picker.
namespace APPiGarbage.Models
{
public class TipoUsuario
{
public int IdTipoUsuario { get; set; }
public string Nome { get; set; }
}
}
For my MVVM Model I tried whole lot codes and now I don't even know what to put in it. To be honest.
namespace APPiGarbage.ViewModel
{
public class UsuarioViewModel
{
public List<TipoUsuario> tipos { get; set; }
public List<Usuario> GetTipos()
{
var tipos = new List<Usuario>()
{
};
return tipos;
}
}
For my ApiService class I have this code:
namespace APPiGarbage.API
{
public class ApiService
{
public const string Url = "http://10.0.2.2:44342/";
public static async Task<List<TipoUsuario>> ObterTipoUsuarios()
{
try
{
HttpClient client = new HttpClient();
string url = Url + "/api/TipoUsuario";
string response = await client.GetStringAsync(url);
List<TipoUsuario> tipos = JsonConvert.DeserializeObject<List<TipoUsuario>>(response);
return tipos;
}
catch (Exception)
{
throw;
}
}
}
}
This is the Picker in my UsuarioPage.xaml:
<Picker Title="Selecione o Tipo de Usuario"
ItemsSource="{Binding TipoUsuario}"
ItemDisplayBinding="{Binding Nome}"/>
And finally this is the UsuarioPage.xaml.cs:
namespace APPiGarbage.Pages.UsuarioPage
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class UsuarioPage : ContentPage
{
public UsuarioPage()
{
InitializeComponent();
BindingContext = new UsuarioViewModel();
}
}
}
Thank you for taking your time to help me.
回答1:
First, in your xaml, your Picker's ItemsSource should bind to the tipos in your ViewModel.
<Picker Title="Selecione o Tipo de Usuario"
ItemsSource="{Binding tipos}"
ItemDisplayBinding="{Binding Nome}"/>
Second, you should get data from Api in ViewModel:
public class UsuarioViewModel
{
public ObservableCollection<TipoUsuario> tipos { get; set; }
public UsuarioViewModel() {
Task<List<TipoUsuario>> task = ApiService.ObterTipoUsuarios();
tipos = new ObservableCollection<TipoUsuario>(task.Result);
}
}
Then the binding should work and feel free to ask me any question if you have.
来源:https://stackoverflow.com/questions/63284584/how-to-load-a-picker-in-xamarin-forms-with-data-received-from-the-web-api