我的模型如下:
public class UserDetails
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool Truck { get; set; }
public bool Car { get; set; }
public bool Bus { get; set; }
}
public class TransportDetails
{
public int Id { get; set; }
public string Name { get; set; }
public string Url{ get; set; }
}
我还定义了一个包含用户详细信息的列表,如下所示:
public List<UserDetails> GetAllUserDetails()
{
List<UserDetails> userDetails = new List<UserDetails>
{
new UserDetails
{
Id = 1,
Username = "admin",
Password = "123",
Truck = false,
Car = true,
Bus = true
},
new UserDetails
{
Id = 2,
Username = "superadmin",
Password = "123",
Truck = true,
Car = false,
Bus = true
}
};
return userDetails;
}
该应用程序的工作原理如下:
到目前为止,已经完成了:
public void CheckLogin()
{
UserData userData = new UserData();
allUsers = new List<UserDetails>();
allUsers = userData.GetAllUserDetails();
if (allUsers.Any(x => x.Username.Equals(Username) && x.Password.Equals(Password)))
{
var user = allUsers.Where(x => x.Username.Equals(Username) && x.Password.Equals(Password)).First();
Application.Current.MainPage.Navigation.PushAsync(new PortalPage(user));
}
else
{
Application.Current.MainPage.DisplayAlert("Error", "Invalid credentials", "OK");
}
}
我希望在用户登录后根据模型UserDetails中的属性为动态显示按钮。然后,当按钮根据此用户的真实情况出现时,我想要按钮名称和按钮来自TransportDetails模型的值(url)。
有人可以告诉我如何实现这个目标吗?
答案 0 :(得分:1)
StackLayout stack = new StackLayout();
if (user.Truck) {
Button truck = new Button();
var transport = transports.Where(t => t.Name == "truck").First();
truck.Text = transport.Name;
truck.Clicked += (sender, e) => { Device.OpenUrl(transport.Url); };
stack.Children.Add(truck);
}
// repeat for other types
如果您修改UserDetails类
public class UserDetails
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public List<TransportDetail> Transport { get; set; }
}
然后你可以这样做
StackLayout stack = new StackLayout();
foreach (var t in user.Transport) {
Button btn = new Button();
btn.Text = t.Name;
btn.Clicked += (sender, e) => { Device.OpenUrl(t.Url); };
stack.Children.Add(btn);
}
答案 1 :(得分:0)
我认为你应该修改你的模型。
对于每个用户,您应该有ObservableCollection<TransportDetail> transportDetail
public class UserDetails
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
ObservableCollection<TransportDetails> TransportDetails{get;set;}
}
然后你应该只向用户添加TransportDetails传输功能。
此时,我建议使用ListView。在每个ViewCell上你都应该有一个Button。将您的属性绑定到此Button。使用trasportDetail
列表