簡體   English   中英

列表框數據綁定不起作用

[英]Listbox Databinding Not working

我無法弄清楚為什么數據綁定不能按預期工作:

  • 我創建了一個列表框,並將其ItemSource設置為可觀察的集合
  • 我用了this.DataContext = this
  • 我初始化了我的公共可觀測集合
  • 我用實現INotifyPropertyChanged的對象填充它

但是,數據綁定仍然無法正常工作。 我的列表框:

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

后面的代碼:

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() }));            
    }        
}

我的自定義類實現了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));
        }
    }
}

您不能綁定到NonProperty:

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

public ObservableCollection<headerInfo> headers;

您需要綁定到以下屬性:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM