Silverlight - DataContext,DataGrid,WCF以及以编程方式添加元素和绑定

时间:2012-05-15 09:43:05

标签: wcf silverlight data-binding silverlight-5.0

我对Silverlight很新。

我有一个带有数据网格和其他表单元素的usercontrol。 我正在尝试以编程方式实现绑定,从WCF服务加载数据。

这就是我所拥有的,我不确定如何让它真正起作用:

public class DepartmentObject
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public IEnumerable<Person> People { get; set; }
}    

public partial class DepartmentView : UserControl
{
    ObservableCollection<Person> LocalPeople { get; set; }
    Service1Client client = new Proj.ServiceReference1.Service1Client();

    public TemplateView(Guid departmentId)
    {
        InitializeComponent();

        client.GetDeptCompleted += (sender, e) =>
        {
            this.DataContext = e.Result; //DepartmentObject w/People member IEnumerable<Person>

            this.peopleList.SetBinding(DataGrid.ItemsSourceProperty, new Binding("People"));

            LocalPeople = new ObservableCollection<Person>(e.Result.People);
        };

        client.GetDeptAsync(departmentId);
    }


    private void Add_Person_Click(object sender, RoutedEventArgs e)
    {
        LocalPeople.Add(new Person() { Name = String.Format("Person [{0}]", LocalPeople.Count) });
    }
}

现在,我理解为什么它不起作用 - 可观察集合和数据上下文之间没有“连接”,但这样做的正确方法是什么?

peopleList是一个DataGrid,当选择一个人时,它将具有二级绑定。

我希望最终能够点击“保存”,并在DepartmentObject中获取所有更改内容。

我经历了很多的例子,所有SL 2-3-4的例子都不同而且令人困惑。

1 个答案:

答案 0 :(得分:0)

我不确定e.Result是否会被持久化。以下应该可以工作:

client.GetDeptCompleted += (sender, e) =>
{
   LocalPeople = new ObservableCollection<Person>(e.Result.People);
   this.peopleList.DataContext = LocalPeople; //DepartmentObject w/People member IEnumerable<Person>
   this.peopleList.SetBinding(DataGrid.ItemsSourceProperty, new Binding("."));
};

在分配LocalPeople后设置断点以确保集合不为空。