0

无法将对象绑定到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:(无路径);数据项=空;目标元素是 'Button' (Name=''); 目标属性是“NoTarget”(类型“对象”)

4

1 回答 1

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)
            {
                // 
            }
        }
于 2013-04-11T18:25:16.730 回答