【问题标题】:ListBox ItemsSource binding path error. What am I missing?ListBox ItemsSource 绑定路径错误。我错过了什么?
【发布时间】:2021-06-23 06:13:17
【问题描述】:

我无法理解遇到的 ListBox ItemsSource 绑定错误。我遵循了 Gong WPF.DragDrop GitHub 项目的详细信息,但在绑定路径上出现此错误:

here 项目是我正在进行的工作并显示了问题。我通过在可观察项目上使用泛型类型进行了一些扩展,因此我可以使 ListBoxItemViewModel 可重用,但我发现没有泛型类型它仍然会失败。

这是用于ListBox 的 XAML。

<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}"/>

这是我的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 有一个名为Items 的公共ObservableCollection 属性,并且一个实例被分配为DataContext 那么为什么ItemsSource="{Binding Items}" 不解析呢?

【问题讨论】:

标签: wpf xaml data-binding .net-5


【解决方案1】:

问题在于ListBoxViewModel&lt;TItemVm&gt; 中的Items 是一个字段,而不是一个属性。

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

像下面这样更改成员,使其成为属性并启用绑定。

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

有关可在 WPF 中使用哪些绑定源的详细信息,请参阅 Binding Source Types

【讨论】:

    猜你喜欢
    • 2012-04-18
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 2015-10-06
    • 2015-10-18
    • 2013-08-01
    相关资源
    最近更新 更多