【问题标题】:Bind result from a Web API Projection request to a WPF Control like DataGrid or ListView将 Web API 投影请求的结果绑定到 DataGrid 或 ListView 等 WPF 控件
【发布时间】: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;
        });

【问题讨论】:

    标签: c# sql wpf linq asp.net-web-api


    【解决方案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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 2015-08-04
      相关资源
      最近更新 更多