2012-05-21 36 views
0

enter image description here我想从WCF服务返回的数据绑定到使用MVVM的WPF中的网格。当我在视图模型中使用WCF服务的逻辑时也是如此。使用MVVM模式绑定WPF网格到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; 
    } 
} 

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

+0

修正了这个问题..缺少数据合同中的DataMember属性 – Arihant

回答

0

是否有任何约束力的错误?或者可能存在serviceide问题,并且该服务不返回任何条目。你调试/断点属性的getter并检查结果?

+0

当从服务中调试时,它显示正确的结果。但是,在VM中,它显示正确的计数,但集合显示扩展数据的成员为空。 – Arihant

+0

扩展数据是什么意思?返回的集合是什么类型?您可以通过右键单击servicereference并选择配置来更改数据类型。 – csteinmueller

+0

它没有显示正在从服务中正确返回的属性..附加到问题 – Arihant

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

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

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

为什么你的解决方案不起作用可能的原因:

  1. 列表不通知的集合变化的图。改用ObservableCollection。

  2. 当学生资产发生变化(var students = new List<Student>(service.GetStudents());)时,没有信号显示该资产已更改;在ViewModel上实现INotifyPropertyChanged。

  3. 确保服务返回数据。

+0

+1的问题; @Arihant:我在想,WPF正在根据您的只读不可观察列表进行一些优化,而不是刷新空白视图。如果将WCF调用移动到构造函数中并将'Students'暴露为'ObservableCollection'并不能解决问题,那么您也可以尝试添加一个setter(我不知道这是必需的还是有帮助的)。 –