[英]How can I get username with userid in generic list wpf C#?
I programing an WPF client application. 我正在编写WPF客户端应用程序。 I have a rest api, the WPF client is communicating with this.
我有一个REST API,WPF客户端正在与此通信。 I made a combobox in wpf, the data binding is ok.
我在wpf中制作了一个组合框,数据绑定正常。
XAML markup: XAML标记:
<ComboBox Name="usernameBox" HorizontalAlignment="Left"
Margin="127,33,0,0" VerticalAlignment="Top" Width="152" Height="24"
ItemsSource="{Binding UserList}" DisplayMemberPath="Username"/>
This is working fine. 一切正常。 But I have one generic list
Userlist
, I am binding this for the combobox. 但是我有一个通用列表
Userlist
,我将其绑定到组合框。 I want that for the username is the combobox I can get a variable with userid. 我希望用户名是组合框,我可以使用用户名获取变量。
Model\\Users class: 模型\\用户类:
namespace Desktop.Model
{
public class Users
{
public int UserId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Fullname { get; set; }
public int Authority { get; set; }
}
}
ViewModel/UserViewModel class: ViewModel / UserViewModel类:
using GalaSoft.MvvmLight;
using Desktop.Model;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using Newtonsoft.Json;
namespace Desktop.ViewModel
{
public class UserViewModel : ViewModelBase
{
public List<Users> UserList { get; set; }
public UserViewModel()
{
UserList = new List<Users>();
string url = "http://localhost:1234/api/users";
var json = new WebClient().DownloadString(url);
UserList = JsonConvert.DeserializeObject<List<Users>>(json);
}
}
}
Get api/users json: 获取api / users json:
[
{
"UserID": 1,
"Username": "admin",
"Password": "password",
"Fullname": "teszt",
"Authority": 1
}
]
Sorry for my bad English. 对不起,我的英语不好。 Please help me!
请帮我! Thank you.
谢谢。
I managed to solve. 我设法解决了。
XAML markup: XAML标记:
<ComboBox x:Name="usernameBox" HorizontalAlignment="Left" Margin="127,33,0,0" VerticalAlignment="Top" Width="152" ItemsSource="{Binding UserList}" SelectedValuePath="UserId" DisplayMemberPath="Username"/>
Codebehind: 代码隐藏:
var id = usernameBox.SelectedValue;
It's working fine! 一切正常!
Using MVVM like you are you can add to your XAML: 像您一样使用MVVM,可以将其添加到XAML中:
SelectedItem="{Binding SelectedUser}"
in your ViewModel: 在您的ViewModel中:
private Users _user;
public Users SelectedUser
{
get
{
return _user;
}
set
{
if (_user == value)
return;
_user = value;
OnPropertyChanged(nameof(SelectedUser));
}
}
Done, use the property SelectedUser
to get your selected " Users
" in your ComboBox 完成后,使用属性
SelectedUser
在ComboBox中获取所选的“ Users
”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.