无法将对象绑定到ListBox

时间:2013-04-11 18:14:09

标签: c# wpf xaml binding listbox

无法将对象绑定到ListBox。数据在那里,我想这是关于Binding

有任何线索吗?

C#

   public sealed class Package
    {
        public Guid ID { get; set; }

        public string FileName { get; set; }

        public List<PackageItem> PackageItems { set; get; }
    }

    public sealed class PackageItem
    {
        public Guid ID { get; set; }

        public string FileName { get; set; }

        public PackageItemTypes PackageItemType { get; set; }
    }

private ObservableCollection<Package> availablePackages;

 lbPackageList.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        lbPackageList.DataContext = availablePackages;
                    }));

XAML

<ListBox Name="lbPackageList"
         VerticalAlignment="Stretch"
         HorizontalAlignment="Stretch"
         ScrollViewer.VerticalScrollBarVisibility="Visible">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Horizontal">
        <Label Content="{Binding Path=Package.FileName}" />
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

错误

  

System.Windows.Data错误:3:找不到提供的元素   DataContext的。 BindingExpression :(没有路径);的DataItem = NULL;目标   元素是'Button'(Name =''); target属性是'NoTarget'(类型   '对象')

1 个答案:

答案 0 :(得分:0)

我找到了解决方案

 lbPackageList.ItemsSource = availablePackages;

 void engine_PackgesChanged(Models.Package newPackage)
        {
            Debug.WriteLine("There is a new package here " + newPackage.FileName);

            try
            {
                lbPackageList.Dispatcher.BeginInvoke((Action)(() =>
                   {
                       if (availablePackages.Contains(newPackage) == false)
                       {
                           availablePackages.Add(newPackage);
                       }
                   }));
            }
            catch (Exception)
            {
                // 
            }
        }