C# 将项添加到列表框后DragDrop中的NullReferenceException

C# 将项添加到列表框后DragDrop中的NullReferenceException,c#,wpf,drag-and-drop,listbox,nullreferenceexception,C#,Wpf,Drag And Drop,Listbox,Nullreferenceexception,我试图实现一个动态列表框,其中包含我的程序的“打开的文件”。这些文件可以从列表框拖动到四个画布中的一个。 只要在启动程序之前将项目添加到XAML中,就可以正常工作,但是,一旦我通过fileList.items.add(“myitemname”)将项目添加到列表框中;如果我试图在此时将它们拖放到画布中,我会得到一个NullReferenceException DragDrop.DoDragDrop(listBox, dragData, DragDropEffects.Move); 下面是我的代码

我试图实现一个动态列表框,其中包含我的程序的“打开的文件”。这些文件可以从列表框拖动到四个画布中的一个。 只要在启动程序之前将项目添加到XAML中,就可以正常工作,但是,一旦我通过fileList.items.add(“myitemname”)将项目添加到列表框中;如果我试图在此时将它们拖放到画布中,我会得到一个NullReferenceException

DragDrop.DoDragDrop(listBox, dragData, DragDropEffects.Move);
下面是我的代码的相关部分:

public partial class MainWindow : Window
{
    InitialDataObject _initData = new InitialDataObject();

    public MainWindow()
    {
        InitializeComponent();
    }


    #region DragImage

    private void DragImageStart(object sender, MouseButtonEventArgs e)
    {
        _initData._mousePoint = e.GetPosition(null);
    }

    private void DragImageMove(object sender, MouseEventArgs e)
    {
        Point mousePos = e.GetPosition(null);
        Vector diff = _initData._mousePoint - mousePos;

        if (e.LeftButton == MouseButtonState.Pressed && (
        Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
        Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance) && ((sender as ListBox).SelectedItem != null))
        {
            var listBox = sender as ListBox;
            var listBoxItem = listBox.SelectedItem;
            DataObject dragData = new DataObject(_initData._dropIdentifier, listBoxItem);
            DragDrop.DoDragDrop(listBox, dragData, DragDropEffects.Move); 
        }

    }

    private void CanvasDrop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(_initData._dropIdentifier))
        {
            var item = e.Data.GetData(_initData._dropIdentifier) as ListBoxItem;
            (sender as Canvas).Background = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
            DropImage(sender as Canvas, item);
            fileList.UnselectAll();
        }
    }

    private void CanvasDragEnter(object sender, DragEventArgs e)
    {
        if (!e.Data.GetDataPresent(_initData._dropIdentifier) || sender == e.Source)
        {
            (sender as Canvas).Background = new SolidColorBrush(Color.FromArgb(255, 240, 240, 240));
            e.Effects = DragDropEffects.None;
        } 
    }

    private void DropImage(Canvas targetCanvas, ListBoxItem item)
    {
        //just to check if I got the right item in this method
        MessageBox.Show(item.Content.ToString());
    }

    private void CanvasDragLeave(object sender, DragEventArgs e)
    {
        if (!e.Data.GetDataPresent(_initData._dropIdentifier) || sender == e.Source)
        {
            (sender as Canvas).Background = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));
        }
    }

    #endregion

    private void sdfsdf(object sender, RoutedEventArgs e)
    {
        fileList.Items.Add("test");
    }
}

class InitialDataObject
{
    public Point _mousePoint = new Point();
    public readonly string _dropIdentifier = "dropIdentifier";
}
XAML:



您知道为什么它使用现有项目,而不使用通过fileList.items.Add(“..”;)添加的项目吗;?另外,对于现有项,请使用fileList.UnselectAll();工作正常,但额外添加的项目保持选中状态,我无法摆脱选中状态。

您的问题
CanvasDrop
方法。您需要ListBoxItem,但需要获取字符串,因为列表框的
SelectedItem
属性对于在xaml中创建的项和动态添加的项具有不同的值。

请提供异常的堆栈跟踪。它显示了代码中异常发生的位置。我在哪里可以找到它?异常发生后,如果有帮助,将选择“DragDrop.DoDragDrop(列表框、dragData、DragDropEffects.Move);”部分。另外,我一直在做测试,如果我删除MessageBox,它不会崩溃。Show有几个地方您使用了
作为画布,比如
发件人作为画布,发件人作为列表框,之后您需要检查null。当发送方不是预期的类型时,它返回null。由于所有内容都与在XAML中运行前添加到列表框的项目完美配合,因此所有内容都应符合预期。如果您愿意,我可以提供XAML和这段代码。好的,有没有办法将ListBoxItems动态添加到ListBox中?因为UnselectAll()似乎对字符串不起作用。Edit:有趣的是,将所有内容改为string而不是ListBoxItem会使其起作用,但不会使用UnselectAll()取消选择;如果项目具有相同的名称。它可以使用不同的名称。这就是如何添加ListBoxItems的答案:fileList.Items.add(new ListBoxItem{Content=“test”});“为动态添加的项赋予不同的名称”是什么意思?出于测试原因,我给所有项赋予了名称“test”(使用fileList.items.Add(“test”);但随后UnselectAll()无效
<Grid Height="Auto" HorizontalAlignment="Stretch" Margin="0,23,0,0" Name="gridSubmain" VerticalAlignment="Stretch" Width="Auto" Panel.ZIndex="2">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="250" MaxWidth="250" MinWidth="250" />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <ListBox Height="Auto" Name="fileList" Width="Auto" Background="#FFE6E6E6" BorderBrush="{x:Null}" Panel.ZIndex="1" PreviewMouseLeftButtonDown="DragImageStart" PreviewMouseMove="DragImageMove" FontSize="16" ItemsSource="{Binding}" Margin="0" Grid.Row="2">
        <ListBoxItem Content="dfgdfg" />
        <ListBoxItem Content="sfsdf" />
        <ListBoxItem Content="ghjgh" />
        <ListBoxItem Content="cvbcvb" />
    </ListBox>
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="112,196,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="sdfsdf" />
</Grid>
<Grid Grid.Column="1" Height="Auto" HorizontalAlignment="Stretch" Margin="0" Name="gridImage" VerticalAlignment="Stretch" Width="Auto">
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
    <Canvas Height="Auto" HorizontalAlignment="Stretch" Margin="0" Name="canvasImage1" VerticalAlignment="Stretch" Width="Auto" AllowDrop="True" Drop="CanvasDrop" DragEnter="CanvasDragEnter" Background="White" DragLeave="CanvasDragLeave" />
    <Canvas Height="Auto" HorizontalAlignment="Stretch" Margin="0" Name="canvasImage2" VerticalAlignment="Stretch" Width="Auto" Drop="CanvasDrop" DragEnter="CanvasDragEnter" Grid.Column="1" AllowDrop="True" Background="White" DragLeave="CanvasDragLeave"/>
    <Canvas Height="Auto" HorizontalAlignment="Stretch" Margin="0" Name="canvasImage3" VerticalAlignment="Stretch" Width="Auto" Drop="CanvasDrop" DragEnter="CanvasDragEnter" Grid.Row="1" AllowDrop="True" Background="White" DragLeave="CanvasDragLeave"/>
    <Canvas Height="Auto" HorizontalAlignment="Stretch" Margin="0" Name="canvasImage4" VerticalAlignment="Stretch" Width="Auto" Drop="CanvasDrop" DragEnter="CanvasDragEnter" Grid.Column="1" Grid.Row="1" AllowDrop="True" Background="White" DragLeave="CanvasDragLeave"/>
</Grid>