WPF入门到精通:4.页面增删改查及调用接口(待完善)

在WPF中,页面的增删改查可以通过使用DataGrid等控件来实现。接口的调用可以使用HttpClient或RestSharp等网络库来完成。

1.页面增删改查

使用DataGrid控件来展示数据,并通过绑定数据源来实现数据的增删改查操作。示例代码如下:

XAML代码:

学生View


  
    
    
    
  

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 students;
    public ObservableCollection 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()
        {
            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>(content);
}

其中,User为服务器返回数据所对应的实体类。反序列化过程中需要使用Newtonsoft.Json库,可通过NuGet进行安装。

另外,如果接口需要进行授权认证,可通过HttpClient的Header属性来添加认证信息:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

你可能感兴趣的:(WPF,wpf)