简体   繁体   English

列表框数据绑定不起作用

[英]Listbox Databinding Not working

I am unable figure out why the databinding is not working as expected: 我无法弄清楚为什么数据绑定不能按预期工作:

  • I created a Listbox and set its ItemSource to my observable collection 我创建了一个列表框,并将其ItemSource设置为可观察的集合
  • I used this.DataContext = this 我用了this.DataContext = this
  • I Initialized my public Observable Collection 我初始化了我的公共可观测集合
  • I filled it with objects that implement INotifyPropertyChanged 我用实现INotifyPropertyChanged的对象填充它

Yet, the databinding, still does not work. 但是,数据绑定仍然无法正常工作。 My Listbox: 我的列表框:

<ListBox Height="425" ItemsSource="{Binding headers}">
  <ListBox.ItemTemplate>
     <DataTemplate>
           <TextBlock Text="{Binding Path=HeaderInfo}"/>
     </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

The code behind: 后面的代码:

public partial class cornet_controls : PhoneApplicationPage
{
    public ObservableCollection<headerInfo> headers;

    public cornet_controls()
    {
        InitializeComponent();
        this.DataContext = this;
        headers = new ObservableCollection<headerInfo>();

        for (int x = 0; x < 100; x++)
            headers.Add((new headerInfo() { HeaderInfo = x.ToString() }));            
    }        
}

My custom class implementing INotifyPropertyChanged: 我的自定义类实现了INotifyPropertyChanged:

public class headerInfo : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public headerInfo()
    {}

    private String _HeaderInfo;

    public String HeaderInfo
    {
        get { return _HeaderInfo; }
        set { _HeaderInfo = value; NotifyPropertyChanged("HeaderInfo"); }
    }

    private void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

You cannot bind to a NonProperty: 您不能绑定到NonProperty:

<ListBox Height="425" ItemsSource="{Binding headers}">

public ObservableCollection<headerInfo> headers;

you need to bind to a Property like: 您需要绑定到以下属性:

public ObservableCollection<headerInfo> headers { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM