めとべや東京 #7で登壇してきましたその1 ストアアプリでListViewに左右のスワイプ処理を追加する

めとべや東京 #7で登壇してきました。

 

AeroPrismの機能の一部を実際にライブコーディングで実装してみようといった内容でしたが、

発表後に「ライブコーディングの内容全部覚えてられない」等の声をいただきましたのでじわじわとブログにまとめていきたいと思います。

 

ストアアプリのTwitterクライアントAeroPrismではツイートを右にスワイプするとリプライ、左にスワイプすると会話のスレッド表示ができます。

f:id:Shinji_Japan:20150120015114p:plain

f:id:Shinji_Japan:20150120015123p:plain

この機能を実装してみましょう。

 

まずはXAML

1.ListViewItemの中にControl(ここではBorder)を配置

2.配置したControlにManipulationDeltaイベントを追加

3.ManipulationModeにはカンマ区切りでTranslateXとSystemを指定

<Page
    x:Class="App25.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App25"
    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}">
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock x:Name="textBlock" FontSize="50" Margin="0,30,0,0"/>
        <ListView x:Name="listView" Grid.Row="1">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Border
                        ManipulationDelta="Border_ManipulationDelta"
                        ManipulationMode="TranslateX,System"
                        Width="300" Height="100" Background="Pink"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Page>

 

つぎにコードの方ですが

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.listView.ItemsSource = Enumerable.Range(0, 100);
        }

        private void Border_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
        {
            if(e.Delta.Translation.X > 10)
            {
                this.textBlock.Text = "Right";//右スワイプ時の処理
            }
            else if(e.Delta.Translation.X < -10)
            {
                this.textBlock.Text = "Left";//左スワイプ時の処理
            }
        }
    }

 

こんな感じ。

ManipulationDeltaRoutedEventArgsのDelta.Translationでスワイプの移動量が取れます。

X方向の移動量が10より大きければ右スワイプ、-10より小さければ左スワイプと判断してそれぞれ処理を追加します。

 

以上で左右のスワイプ処理が追加できます。

 

追記:

Border_ManipulationDeltaの引数senderにはスワイプしたBorderが渡ってきます。

ItemのViewModelは(sender as Border).DataContextで取得可能です。

また、このままだと指でスワイプした場合もマウスでドラッグした場合も処理が行われるので必要であればe.PointerDeviceTypeで判断してください。