WPF在lixbox wrappanel中拖放图像/标签

时间:2015-08-29 01:57:09

标签: c# wpf

我试图让我的图像在listxbox-wrappanel中可拖动,能够在画布中移动图像。

我在这里跟踪样本,但仍然无法正常工作 http://www.codeproject.com/Tips/442276/Drag-and-Drop-WPF-Controls

以下是我的代码:

XAML

<Canvas Name="canvastTable" Grid.Row="1" Margin="100,10,10,4" Panel.ZIndex="99" Background="Gold" AllowDrop="True" MouseMove="canvastTable_MouseMove">
            <ListBox Name="lbTable" HorizontalAlignment="Left" Height="267" BorderBrush="White" Background="Green" BorderThickness="2" 
            VerticalAlignment="Top" Width="889" Panel.ZIndex="9999" Grid.Row="1" ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
            Canvas.Left="10" Canvas.Top="10">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Image Source="C:\img\mcd.jpg" Width="100" Height="100" Margin="10" Cursor="Hand" AllowDrop="True" 
                            PreviewMouseLeftButtonDown="lbTable_PreviewMouseLeftButtonDown" PreviewMouseLeftButtonUp="lbTable_PreviewMouseLeftButtonUp" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
                <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel Orientation="Horizontal" IsItemsHost="True" AllowDrop="True" />
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>
            </ListBox>
        </Canvas>

代码背后:

double FirstXPos, FirstYPos;
        object MovingObject;

        private void lbTable_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            FirstXPos = e.GetPosition(sender as Control).X;
            FirstYPos = e.GetPosition(sender as Control).Y;
            MovingObject = sender;

            MessageBox.Show("click");
        }

        private void lbTable_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            MovingObject = null;
            MessageBox.Show("up");
        }

        private void canvastTable_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                (MovingObject as FrameworkElement).SetValue(Canvas.LeftProperty,
                                        e.GetPosition((MovingObject as FrameworkElement).Parent as FrameworkElement).X - FirstXPos);

                (MovingObject as FrameworkElement).SetValue(Canvas.TopProperty,
                        e.GetPosition((MovingObject as FrameworkElement).Parent as FrameworkElement).Y - FirstYPos);

                MessageBox.Show("move");
            }

        }

0 个答案:

没有答案