在WPF中,页面的增删改查可以通过使用DataGrid等控件来实现。接口的调用可以使用HttpClient或RestSharp等网络库来完成。
1.页面增删改查
使用DataGrid控件来展示数据,并通过绑定数据源来实现数据的增删改查操作。示例代码如下:
XAML代码:
学生View
<DataGrid ItemsSource="{Binding Students}" SelectedItem="{Binding SelectedItem}">
<DataGrid.Columns>
<DataGridTextColumn Header="学号" Binding="{Binding ID}" />
<DataGridTextColumn Header="姓名" Binding="{Binding Name}" />
<DataGridTextColumn Header="年龄" Binding="{Binding Age}" />
</DataGrid.Columns>
</DataGrid>
C#代码:
学生实体Model
public class Student
{
public string ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
ViewModel
public class MainViewModel : ViewModelBase
{
private ObservableCollection<Student> students;
public ObservableCollection<Student> Students
{
get { return students; }
set
{
students = value;
PCEH();
}
}
private Student studentModel;
public Student StudentModel
{
get { return studentModel; }
set
{
studentModel= value;
PCEH();
}
}
public MainViewModel()
{
Students = new ObservableCollection<Student>()
{
new Student() { ID = "001", Name = "张三", Age = 18 },
new Student() { ID = "002", Name = "李四", Age = 19 },
new Student() { ID = "003", Name = "王五", Age = 20 }
};
}
public void AddStudent(Student student)
{
Students.Add(student);
}
public void RemoveStudent(Student student)
{
Students.Remove(student);
}
public void UpdateStudent(Student student)
{
var oldStudent = Students.FirstOrDefault(s => s.ID == student.ID);
if (oldStudent != null)
{
oldStudent.Name = student.Name;
oldStudent.Age = student.Age;
}
}
}
2.调用接口
使用HttpClient库发送HTTP请求,并通过反序列化方式来解析服务器返回的数据。示例代码如下:
var client = new HttpClient();
var response = await client.GetAsync("http://api.example.com/users");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var users = JsonConvert.DeserializeObject<List<User>>(content);
}
其中,User为服务器返回数据所对应的实体类。反序列化过程中需要使用Newtonsoft.Json库,可通过NuGet进行安装。文章来源:https://www.toymoban.com/news/detail-661086.html
另外,如果接口需要进行授权认证,可通过HttpClient的Header属性来添加认证信息:文章来源地址https://www.toymoban.com/news/detail-661086.html
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
到了这里,关于WPF入门到精通:4.页面增删改查及调用接口(待完善)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!