Sunday, December 28, 2014

How to move or swap two GridView items?


<Page
x:Class="GridViewItemSwap.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:GridViewItemSwap"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<GridView x:Name="gridview" IsItemClickEnabled="True" ItemClick="gridview_ItemClick" >
<GridView.ItemTemplate >
<DataTemplate >
<Border Margin="12" Width="100" Height="100" Background="Blue" >
<TextBlock Text="{Binding}"/>
</Border>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
</Page>




namespace GridViewItemSwap
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private int? firstvalue;
private ObservableCollection<Int32> data = new ObservableCollection<int>();
public MainPage()
{
this.InitializeComponent();
for(int i =0 ; i <4; i++)
{
data.Add(i);
}
gridview.ItemsSource = data;
}

private void gridview_ItemClick(object sender, ItemClickEventArgs e)
{
if (firstvalue.HasValue )
{
Int32 secondvalue = (Int32)e.ClickedItem;
var firstindex= data.IndexOf(firstvalue.Value);
var secondindex = data.IndexOf(secondvalue);
data[firstindex] = secondvalue;
data[secondindex] = firstvalue.Value ;
firstvalue = null;

}
else
{
firstvalue = (Int32)e.ClickedItem;
}

}
}
}





在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。


No comments:

Post a Comment