在windows phone中的用户控件的列表框中绑定数据

时间:2012-08-03 09:25:24

标签: wpf silverlight windows-phone-7 windows-phone-7.1

public class Emp
    {
        public string Id { get; set; }

    }

I declared the class like this, but property i didnt set. I set the dependency property for textblock

 public static readonly DependencyProperty LabelProperty
  = DependencyProperty.Register("TextBlock", typeof(string), typeof(WindowsPhoneControl1), new PropertyMetadata(new PropertyChangedCallback(LabelChanged)));

 public string List
    {
        get { return (string)GetValue(LabelProperty); }
        set { SetValue(LabelProperty, value); }
    }

1 个答案:

答案 0 :(得分:1)

这可能不是答案,但您的代码存在根本性的错误。

将ListBox的ItemSource属性绑定到属性Emp。然后在Click处理程序中,将类型为Emp的对象添加到ListBox的Items属性中。这不起作用。

为了使其与绑定一起使用,必须有一些可枚举类型的属性EmpList,最好是ObservableCollection。绑定还需要知道定义此属性的(模型)对象。因此,您必须设置ListBox的DataContext或指定绑定的Source

向数据绑定ListBox添加元素时,不要将它们添加到Items,而是添加到绑定的source属性EmpList

public class Model
{
    private ICollection<Emp> empList = new ObservableCollection<Emp>();

    public ICollection<Emp> EmpList { get { return empList; }}
}

这样绑定:

<ListBox ItemsSource="{Binding EmpList, Source={ an instance of Model }}" ... /> 

或者如下所示

<ListBox Name="listBox" ItemsSource="{Binding EmpList}" ... />

并设置DataContext,可能在代码中:

listBox.DataContext = model; // where model is an instance of class Model

for (int i = 0; i < result.Length; i++)        
{        
    Emp data = new Emp { Id = result[i] };
    model.EmpList.Add(data);
}
相关问题