将 Web API 投影请求的结果绑定到 DataGrid 或 ListView 等 WPF 控件

Posted

技术标签:

【中文标题】将 Web API 投影请求的结果绑定到 DataGrid 或 ListView 等 WPF 控件【英文标题】:Bind result from a Web API Projection request to a WPF Control like DataGrid or ListView 【发布时间】:2020-01-13 08:18:45 【问题描述】:

我正在尝试编写 Web API 的客户端部分 并以用户友好的模式使用这些请求。 我为服务器部分编写了控制器,现在我正在尝试显示查询的数据。

使用投影,我不能使用 EDM 类型(学生),因为我不知道用户会请求什么属性,所以我设法使用 ExpandoObject 并只添加客户端在 UI 中检查的那些属性

现在 ExpandoObject 实现了 IDictionary 接口,您可以从中访问每个动态属性。

有什么方法可以从 Web API 方法返回的 IEnumerable> 类型填充 ListView 或 DataGrid? (IEnumerable 因为我有一个从数据库生成的学生列表) 这就是我只获取请求的列的方式:

   return db.Students.AsEnumerable().Select(student =>
        
            IDictionary<string, object> expandoStudent = new ExpandoObject();

            foreach (var property in properties)
                expandoStudent.Add(property.Name, property.GetValue(student, null));

            return expandoStudent;
        );

【问题讨论】:

【参考方案1】:

是的,您可以填写 ListViewDataGrid

要以更具交互性的方式进行操作,最好使用 ObservableCollection 作为 ListView 的项目来源,这将在您的项目列表中添加新项目时更新您的 UI。

并且实际的 DataBinding 与 Xamarin DataBinding 的工作方式类似,只是略有不同。

示例如下:

public ListView()

    this.Student = new ObservableCollection();
    InitializeComponent();
    this.DataContext = this;

    // And here you actually add your items to the collection

    this.Student.Add(new IDictionary<string, object>("Key01", MyObject));

this 指的是您的 ListView 模型。

ObservableCollection 将在您添加到集合中的每个新项目后运行一个事件来更新您的 UI。

【讨论】:

以上是关于将 Web API 投影请求的结果绑定到 DataGrid 或 ListView 等 WPF 控件的主要内容,如果未能解决你的问题,请参考以下文章

将对象绑定到 Web API 端点时指定自定义属性名称

处理 ASP.NET Core Web API 对象属性绑定

Epson投影仪的远程身份验证

Angular JS 将结果从 api 绑定到下拉菜单

使用 web api 编辑获取数据时无法将数据绑定到 jqgrid 中的下拉列表

来自json的web api 2绑定模型