wcf - 使用 MVVM 模式将 WPF 网格绑定(bind)到 WCF 服务

标签 wcf mvvm wpfdatagrid

enter image description here我正在尝试使用 MVVM 将从 WCF 服务返回的数据绑定(bind)到 WPF 中的网格。当我在 View 模型中使用 WCF 服务的逻辑时也是如此。

隐藏代码:

this.DataContext = new SampleViewModel();

查看/XAML:
<Window x:Class="Sample.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
 <Grid>
    <DataGrid ItemsSource="{Binding Students}" AutoGenerateColumns="False" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding ID}" />
            <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
            <DataGridTextColumn Header="Address" Binding="{Binding Address}" />
        </DataGrid.Columns>
    </DataGrid>
 </Grid>
</Window>

查看型号:
public List<Student> Students {
        get {
            var service = new StudentServiceClient();
            var students = new List<Student>(service.GetStudents());
            return students;
        }
    }

IStudentService:
[ServiceContract]
public interface IStudentService {
    [OperationContract]
    IEnumerable<Student> GetStudents();
}

[DataContract]
public class Student {
    public string Name { get; set; }

    public int ID { get; set; }

    public string Address { get; set; }
}

StudentService.svc:
public class StudentService : IStudentService {
    public IEnumerable<Student> GetStudents() {
        var students = new List<Student>();

        for (int i = 0; i < 3; i++) {
            students.Add(new Student {
                Name = "Name" + i,
                ID = i,
                Address = "Address" + 1
            });
        }

        return students;
    }
}

当我运行该应用程序时,我没有在网格中看到 Ant 记录..

最佳答案

public List<Student> Students {
    get {
        var service = new StudentServiceClient();
        var students = new List<Student>(service.GetStudents());
        return students;
    }
}

每次使用/读取学生属性时,此代码将连接到服务器并检索学生。那会太慢了。

在 ViewModel 的构造函数中(或在单独的方法/命令中)加载学生,并从 getter 中返回此集合。

您的解决方案不起作用的原因可能是:
  • List 不会通知 View 集合的变化;改用 ObservableCollection。
  • 当 Students 属性更改 (var students = new List<Student>(service.GetStudents()); ) 时, View 没有信号表明该属性已更改;在 ViewModel 上实现 INotifyPropertyChanged。
  • 确保服务返回数据。
  • 关于wcf - 使用 MVVM 模式将 WPF 网格绑定(bind)到 WCF 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10682250/

    相关文章:

    asp.net-mvc - 使用 WCF/OData 作为访问层而不是直接使用 EF/L2S/nHibernate 的论点

    javascript - 如何在 jQuery 中使用 WCF 方法

    c# - Wpf Observable 集合和 DataGrid 不更新更改

    wpf - 当列已排序时编辑 WPF 数据网格组合框列时,对象未设置为对象的实例

    WPF DataGrid - 如果存在无效单元格,如何停止用户继续操作? (MVVM)

    WPF:在 DataTable、MVVM 方式中更改列后刷新 DataGrid

    c# - 在 IIS 上托管在 VS2010 中创建的 WCF 服务

    c# - WPF mvvm 信使析构函数

    c# - WPF MVVM Binding Checkbox.IsChecked 到 Dictionary<string, bool> 中的命名项

    c# - WCF With NetTCP 跨同一网络上的机器