@sofronov

В чем различие в Binding у Control и Template (на примере GongSolutions.Wpf.DragDrop )?

Разбираюсь с устройством MVVM, хочу прикрутить Drag`n`Drop к окну с контролами, привязанными к вьюмодели. В окне создаю вроде одинаковые ListBox, один напрямую, несколько по шаблону из списка:
<Window x:Class="WpfDragDropTestApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:dd="clr-namespace:GongSolutions.Wpf.DragDrop;assembly=GongSolutions.Wpf.DragDrop"
        xmlns:local="clr-namespace:WpfDragDropTestApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:SimpleViewModel/>
    </Window.DataContext>

    <Window.Resources>
        <DataTemplate x:Key="MyItemTemplate"  DataType="{x:Type local:ItemVisualisation}">
            <Grid>
                <Ellipse Stroke="Black"
                             StrokeThickness="1"
                             Height="{Binding VisualDiameter}"
                             Width="{Binding VisualDiameter}"
                             >
                </Ellipse>
            </Grid>
        </DataTemplate>

        <DataTemplate x:Key="MyControlDataTemplate" DataType="{x:Type local:MyListVisualisation}">
            <ListBox Margin="0"
				Width="{Binding VisualWidth}"
				Height="{Binding  VisualHeight}"
                        	dd:DragDrop.IsDragSource="True"
				dd:DragDrop.IsDropTarget="True"
                        	dd:DragDrop.DropHandler="{Binding}"
                        	dd:DragDrop.DragAdornerTemplate="{StaticResource MyItemTemplate}"
				ItemTemplate="{StaticResource MyItemTemplate}" 
                        >
            </ListBox>
        </DataTemplate>

    </Window.Resources>

    <StackPanel >
        <ListBox ItemTemplate="{StaticResource MyControlDataTemplate}"
                        ItemsSource="{Binding ListsCollection}"
            >
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"></StackPanel>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ListBox>
        <ListBox Margin="0"
                 Height="100"
                 ItemsSource="{Binding ItemsCollection}"
                 dd:DragDrop.IsDragSource="True"
                 dd:DragDrop.IsDropTarget="True"
                 dd:DragDrop.DropHandler="{Binding}"
                 dd:DragDrop.DragAdornerTemplate="{StaticResource MyItemTemplate}"
                 ItemTemplate="{StaticResource MyItemTemplate}" 
                >
        </ListBox>
    </StackPanel>
</Window>


Модель привязана непосредственно к окну.
using GongSolutions.Wpf.DragDrop;
using System.Collections.ObjectModel;

namespace WpfDragDropTestApp
{
    public class SimpleViewModel : DefaultDropHandler
    {
        public ObservableCollection<MyListVisualisation> ListsCollection { get; private set; }
        public ObservableCollection<ItemVisualisation> ItemsCollection { get; private set; }

        public override void Drop(IDropInfo dropInfo)
        {
            base.Drop(dropInfo);
        }

        public SimpleViewModel()
        {
            ListsCollection = new ObservableCollection<MyListVisualisation>();
            ListsCollection.Add(new MyListVisualisation() { VisualHeight = 200, VisualWidth = 400 });
            ListsCollection.Add(new MyListVisualisation() { VisualHeight = 250, VisualWidth = 250 });

            ItemsCollection = new ObservableCollection<ItemVisualisation>();
            ItemsCollection.Add(new ItemVisualisation() { VisualDiameter = 20 });
            ItemsCollection.Add(new ItemVisualisation() { VisualDiameter = 30 });
            ItemsCollection.Add(new ItemVisualisation() { VisualDiameter = 20 });
            ItemsCollection.Add(new ItemVisualisation() { VisualDiameter = 10 });
        }
    }
}

Само перетаскивание при этом прекрасно работает. Элементы перетаскиваются и внутри каждого контрола и между любыми контролами.
Вопрос заключается в том, что унаследованный обработчик Drop вызывается только при "отпускании" внутри явно объявленного контрола, но не при отпускании внутри "шаблонных".
Собственно очень хочется понять почему и как исправить?
  • Вопрос задан
  • 49 просмотров
Решения вопроса 1
@sofronov Автор вопроса
Сам спросил, сам ответил.
Всё дело в DataContext. У созданных по шаблону контролов он смотрел в другое место. Пришлось указать вручную (запустив поиск по типу) и всё заработало.
dd:DragDrop.DropHandler="{Binding Path=DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы