Wpf空ListBox模板+拖放



在WPF列表框空数据模板的答案之后,我将TextBlock垂直和水平对齐到中心。

然而,当显示空模板时,我不能将项目拖放到ListBox 中,除非我将鼠标放在实际的TextBlock上。我希望能够在列表框内的任何位置拖动项目。

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);
        }
    }
}
}

我使用gong-wpf-dragdrop lib。有人知道怎么解吗?

你应该给你的自定义模板一个背景,以允许目标在整个客户端大小。

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

希望这对你有帮助!

最新更新