我正在尝试在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:路径= DataContext.DropCommand;的DataItem = NULL; target元素是'MyDragDropBehavior'(HashCode = 25707777); target属性是'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}">
但我仍然不明白为什么以前的方法不起作用。如果有人知道,我会很感激。