0

我正在尝试像这样在 RadListBox 的 DragDropBehavior 中使用绑定

    <UserControl xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"  x:Class="MyProject.Views.MyView"
                 ....
                 xmlns:behaviors="clr-namespace:MyProject.Behaviors"
                 mc:Ignorable="d"
                 d:DesignHeight="300" d:DesignWidth="300">
   <Grid>
        ...
        <telerik:RadListBox ItemsSource="{Binding Items}">
                    <telerik:RadListBox.DragDropBehavior>
                        <behaviors:MyDragDropBehavior AllowReorder="True" DropCommand="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.DropCommand}"/>
                    </telerik:RadListBox.DragDropBehavior>
        </telerik:RadListBox>
    </Grid>
</UserControl>

View 通过注入获取 viewmodel

public partial class MyView : UserControl 
    {
        public MyView (ViewModels.MyViewModel viewModel)
        {
            InitializeComponent();
            DataContext = viewModel;
        }
    }

行为代码:

public class MyDragDropBehavior : Telerik.Windows.DragDrop.Behaviors.ListBoxDragDropBehavior
    {
        public override bool CanDrop(Telerik.Windows.DragDrop.Behaviors.DragDropState state)
        {
            return state.IsSameControl;
        }

        public override void Drop(Telerik.Windows.DragDrop.Behaviors.DragDropState state)
        {
            base.Drop(state);
            DropCommand.Execute(null);
        }

        public ICommand DropCommand
        {
            get { return (ICommand)GetValue(DropCommandProperty); }
            set { SetValue(DropCommandProperty, value); }
        }

        public static readonly DependencyProperty DropCommandProperty =
            DependencyProperty.Register("DropCommand", typeof(ICommand), typeof(MyDragDropBehavior), new PropertyMetadata(null));
    }

项目绑定运行良好。行为有效,但绑定到 DropCommand 无效。我得到绑定错误:

无法通过引用 'RelativeSource FindAncestor,AncestorType='System.Windows.Controls.UserControl',AncestorLevel='1'' 找到绑定源。BindingExpression:Path=DataContext.DropCommand; 数据项=空;目标元素是“MyDragDropBehavior”(HashCode=25707777);目标属性是“DropCommand”(类型“ICommand”)

ViewModel 是

public class MyViewModel
    {
        public MyViewModel()
        {
            DropCommand = new DelegateCommand(OnDrop);
            Items = new ObservableCollection<MyItem>();
        }

        public ObservableCollection<MyItem> Items { get; set; }

        public DelegateCommand DropCommand { get; set; }

        private void OnDrop()
        {

        }
    }

怎么了?

我通过以下方式找到了解决问题的方法

<telerik:RadListBox DragDropBehavior="{Binding DragDropBehavior}">

但我仍然不明白为什么以前的方法不起作用。如果有人知道,我将不胜感激。

4

0 回答 0