1

我对 Silverlight 很陌生。

我有一个带有数据网格和其他表单元素的用户控件。我正在尝试以编程方式实现绑定,从 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 示例都不同且令人困惑。

4

1 回答 1

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 后设置断点以确保集合不为空。

于 2012-05-15T09:59:42.447 回答