Win 8中WPF listview与listBox的Drag、Drop操作
Posted on 2012-02-29 18:06 work hard work smart 阅读(3238) 评论(1) 编辑 收藏 举报Win 8中WPF listview与listBox的Drag、Drop操作。
基本原理是将listview中的项拖动到listBox中。
界面:
<UserControl x:Class="DragTitleToWebView.MainPage" 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" mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="1366"> <Grid x:Name="LayoutRoot" Background="#FF0C0C0C"> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="5*"/> </Grid.ColumnDefinitions> <ListView Grid.Column="0" AllowDrop="True" CanDragItems="True" CanReorderItems="True" DragItemsStarting="ListView_DragItemsStarting" > <ListView.Resources> <Style TargetType="Rectangle"> <Setter Property="Width" Value="100"/> <Setter Property="Height" Value="100"/> </Style> </ListView.Resources> <Rectangle Fill="Orange" Tag="Rect1" Width="100" Height="100"/> <Rectangle Fill="Orange" Tag="Rect2" Width="120" Height="120"/> <Rectangle Fill="Orange" Tag="Rect3" Width="140" Height="140"/> <Rectangle Fill="Orange" Tag="Rect4" Width="160" Height="160"/> </ListView> <ListBox x:Name="lb" Grid.Column="1" Margin="10"> </ListBox> <Rectangle Margin="10" x:Name="droppanel" Opacity="0.01" Visibility="Collapsed" Grid.Column="1" AllowDrop="True" Drop="droppanel_Drop" Fill="Green"/> </Grid> </UserControl>
Code:
using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Shapes; partial class MainPage { private bool flag = false; public MainPage() { InitializeComponent(); } private void ListView_DragItemsStarting(object sender, DragItemsStartingEventArgs e) { e.Data.SetText("t", (e.Items[0] as Rectangle).Tag.ToString()); e.Data.SetText("width", (e.Items[0] as Rectangle).Width.ToString()); e.Data.SetText("height", (e.Items[0] as Rectangle).Height.ToString()); droppanel.Visibility = Windows.UI.Xaml.Visibility.Visible; lb.Visibility = Windows.UI.Xaml.Visibility.Collapsed; if (flag) { lb.Visibility = Windows.UI.Xaml.Visibility.Visible; } } private void droppanel_Drop(object sender, DragEventArgs e) { string tag = e.Data.GetText("t"); //如果已经有相同的item,则返回 foreach (Rectangle item in lb.Items) { if (item.Tag.ToString() == tag) { return; } } int width = int.Parse(e.Data.GetText("width")); int height = int.Parse(e.Data.GetText("height")); Rectangle rect = new Rectangle(); rect.Tag = tag; rect.Height = height; rect.Width = width; SolidColorBrush b = new SolidColorBrush(Colors.Orange); rect.Fill = b; lb.Items.Add(rect); droppanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed; lb.Visibility = Windows.UI.Xaml.Visibility.Visible; flag = true; } }
如图:Win 8中是全屏,这里只是图片的一部。
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!