【问题标题】:Listbox Databinding Not working列表框数据绑定不起作用
【发布时间】:2014-01-13 13:57:52
【问题描述】:

我无法弄清楚为什么数据绑定没有按预期工作:

  • 我创建了一个列表框并将其 ItemSource 设置为我的可观察集合
  • 我使用了 this.DataContext = this
  • 我初始化了我的公共 Observable 集合
  • 我用实现 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));
        }
    }
}

【问题讨论】:

    标签: c# data-binding listbox


    【解决方案1】:

    您不能绑定到非属性:

    <ListBox Height="425" ItemsSource="{Binding headers}">
    
    public ObservableCollection<headerInfo> headers;
    

    您需要绑定到如下属性:

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

    【讨论】:

      猜你喜欢
      • 2014-04-04
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多