-2

I've having trouble understanding a ListBox ItemsSource binding error I'm getting. I followed the details on the Gong WPF.DragDrop GitHub project but I'm getting this error on my binding path:

Application with empty ListBox.

XAML Binding Failures window in Visual Studio with "Items property not found [...]" error.

The project here is what I'm working on and shows the issue. I've extended a little by using a generic type on my observable item so i can make the ListBoxItemViewModel reusable but I found that going without the generic type it still fails.

This is the XAML used for the ListBox.

<ListBox Width="300px" x:Name="clothingItems" Margin="10px" AllowDrop="True"
         ItemsSource="{Binding Items}"
         dd:DragDrop.IsDragSource="True"
         dd:DragDrop.IsDropTarget="True"
         dd:DragDrop.DragHandler="{Binding}"/>

This is the code for my ListBoxViewModel.

public class ListBoxViewModel<TItemVm> : IDropTarget
        where TItemVm : class, IDropTargetItemViewModel<TItemVm>
{
    public ObservableCollection<TItemVm> Items = new ObservableCollection<TItemVm>();

    public void DragOver(IDropInfo dropInfo)
    {
        var sourceItem = dropInfo.Data as TItemVm;
        var targetItem = dropInfo.TargetItem as TItemVm;

        if (sourceItem != null && targetItem != null && targetItem.CanAcceptChildren)
        {
            dropInfo.DropTargetAdorner = DropTargetAdorners.Highlight;
            dropInfo.Effects = System.Windows.DragDropEffects.Copy;
        }

    }

    public void Drop(IDropInfo dropInfo)
    {
        var sourceItem = dropInfo.Data as TItemVm;
        var targetItem = dropInfo.TargetItem as TItemVm;

        targetItem.Children.Add(sourceItem);

    }
}

ListBoxViewModel has a public ObservableCollection property called Items and an instance is assigned as the DataContext so why wouldn't ItemsSource="{Binding Items}" resolve?

thatguy
  • 21,059
  • 6
  • 30
  • 40
Stephen York
  • 1,247
  • 1
  • 13
  • 42
  • Duplicate of [Why does WPF support binding to properties of an object, but not fields?](https://stackoverflow.com/questions/842575/why-does-wpf-support-binding-to-properties-of-an-object-but-not-fields). – Clemens Jun 23 '21 at 06:48

1 Answers1

2

The issue is that Items in ListBoxViewModel<TItemVm> is a field, not a property.

public ObservableCollection<TItemVm> Items = new ObservableCollection<TItemVm>();

Change the member like below to make it a property and enable binding it.

public ObservableCollection<TItemVm> Items { get; } = new ObservableCollection<TItemVm>();

See Binding Source Types for more information on which binding sources can be used in WPF.

thatguy
  • 21,059
  • 6
  • 30
  • 40