JobaDiniz JobaDiniz - 3 months ago 72
C# Question

Wpf empty ListBox template + drag-and-drop

Following WPF listbox empty datatemplate answer, I vertical and horizontal aligned the TextBlock to center.

However, when the empty template is shown, I cannot drag and drop items into the ListBox, except when I mouse over the actual TextBlock. I want to be able to drag item in any place inside ListBox.

MainWindow.xaml

<Window x:Class="EmptyListBoxWithDragAndDrop.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:gong="clr-namespace:GongSolutions.Wpf.DragDrop;assembly=GongSolutions.Wpf.DragDrop"
Title="MainWindow" Height="600" Width="800" WindowStartupLocation="CenterScreen">

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>

<ListBox Grid.Column="0" ItemsSource="{Binding Source}"
gong:DragDrop.IsDragSource="True"/>

<ListBox Grid.Column="1" ItemsSource="{Binding Target}"
AllowDrop="True" gong:DragDrop.IsDropTarget="True" gong:DragDrop.DropHandler="{Binding}">
<ListBox.Style>
<Style TargetType="ListBox" BasedOn="{StaticResource {x:Type ListBox}}">
<Style.Triggers>
<Trigger Property="HasItems" Value="False">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<TextBlock Text="Drag items from left ListBox" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.Style>
</ListBox>
</Grid>




ViewModel.cs

using GongSolutions.Wpf.DragDrop;
using System.Collections.ObjectModel;

namespace EmptyListBoxWithDragAndDrop
{
public class ViewModel : IDropTarget
{
public ViewModel()
{
Source = new ObservableCollection<string>();
Target = new ObservableCollection<string>();

Source.Add("Item 1");
Source.Add("Item 2");
Source.Add("Item 3");
Source.Add("Item 4");
Source.Add("Item 5");
Source.Add("Item 6");
Source.Add("Item 7");
}

public ObservableCollection<string> Source { get; private set; }
public ObservableCollection<string> Target { get; private set; }

public void DragOver(IDropInfo dropInfo)
{
if (dropInfo.Data is string)
dropInfo.Effects = System.Windows.DragDropEffects.Copy;
}

public void Drop(IDropInfo dropInfo)
{
if (dropInfo.Data is string)
{
Target.Add((string)dropInfo.Data);
}
}
}
}


I'm using gong-wpf-dragdrop lib. Anyone know how to solve this?

Answer

You should give your custom template a background to allow target drop at the whole client size.

<ControlTemplate>
    <Grid Background="{TemplateBinding Background}">
        <TextBlock Text="Drag items from left ListBox" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    </Grid>
</ControlTemplate>

Hope this helps!

Comments