これは
XAML Advent Calendar 2014 の14日目の記事です。昨日は
@saka_pon さんでした。皆さんネタが濃いです。この記事は残念ながら濃くはないです。長いですけど(すいません)。
1. 前置き
さて、XAMLのコントロールも色々ありますが、個人的にはItemsControlというか、ListViewが好きです。データソースを繋げたらバインディングが張られた子コントロールがだだっと自動生成されるのがたまらない、というか。アプリを作るときは初めてこれを見るのが楽しみだったりします。
このItemsControlの子コントロールは縦横に並べて配置するのが基本ですが、データソースに含まれる情報、例えば地理的な位置情報がある場合は、UI的にそれを生かした地理的な配置にすることも考えられます。それで地理的な配置にした場合、多様なサイズの画面で使えるようにするにはズームが必要になりますし、ズームすれば今度はムーブも必要になり、さらに画面の回転も考慮する必要が出てきます。
そういったものをWindowsストアアプリのWinRTで一式作ってみようというのが、この記事の目的です。
流れとしては以下のようになります。
地理的な配置にする
ビヘイビアを用意する
ズームできるようにする
ムーブできるようにする
回転やサイズ変更や終了後の復元ができるようにする
最終的なものは以下のような感じです。記事とは関係ないですが、日本全国の気温(
OpenWeatherMap による)と各電力会社の電力使用状況をデータとして利用しています。
ソースコードはGitHubに置きました。
2.1. 地理的な配置にする
子コントロールを自由に配置するには、定番ですがListViewのItemsPanelにCanvasを使います。まず子コントロール用のViewModelとして以下のChildViewModelがあるとします。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ChildViewModel
{
public string Name { get; set; }
public double Left { get; set; }
public double Top { get; set; }
public int ZIndex { get; set; }
}
このLeft、Top、ZIndexをそれぞれCanvasの添付プロパティにバインドしてやればいいわけです(ZIndexはもし必要があれば)。
このChildViewModelを要素とするCoreという名のObservableCollectionがあるとして、これをItemsSourceにしたListViewのXAMLがどうなるかというと、WPFの場合は以下のようになります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ListView ItemsSource="{Binding Core}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
<Setter Property="Canvas.Top" Value="{Binding Top}"/>
<Setter Property="Canvas.ZIndex" Value="{Binding ZIndex}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<Border>
<ContentPresenter/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Background="Black">
<TextBlock Margin="10"
Foreground="White"
Text="{Binding Name}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
一応これのポイントはItemContainerStyleのプロパティとしてCanvasの添付プロパティを設定し、これらにChildViewModelからバインドしていることです。ItemContainerStyleが適用されるListViewItemがItemTemplateが適用されるコントロールの親になるので、こちらに設定しないとCanvasに届かないわけですね。
で、この方法はWinRTでは通用しません。なぜならItemContainerStyleにバインディングが通らないから。
ではどうするかというと、いきなりコードビハインドですがItemsControl.PrepareContainerForItemOverrideメソッドを使ってバインディングを張ってやります。これを簡単にやるにはListViewの派生クラスを作ればいいので、CanvasListViewというクラスを作ります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CanvasListView : ListView
{
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
var container = (ListViewItem)element;
container.SetBinding(
Canvas.LeftProperty,
new Binding
{
Path = new PropertyPath("Left"),
Mode = BindingMode.OneWay
});
container.SetBinding(
Canvas.TopProperty,
new Binding
{
Path = new PropertyPath("Top"),
Mode = BindingMode.OneWay
});
container.SetBinding(
Canvas.ZIndexProperty,
new Binding
{
Path = new PropertyPath("ZIndex"),
Mode = BindingMode.OneWay
});
base.PrepareContainerForItemOverride(element, item);
}
}
これを使ったWinRTのListViewのXAMLは以下のようになります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<CanvasListView ItemsSource="{Binding Core}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<Border>
<ContentPresenter/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Grid Background="Black">
<TextBlock Margin="10"
Foreground="White"
Text="{Binding Name}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</CanvasListView>
まあ不要なItemContainerStyleのプロパティを削っただけですが。ItemContainerStyle自体は残しているのは標準のStyleを無効にするためです。
2.2. ビヘイビアを用意する
ズーム/ムーブできるようにするには、これも定番ですがListViewをScrollViewerで囲みます。その準備として、ScrollViewerに関係する処理をBehaviors SDK (XAML)のビヘイビア(要はBlendのビヘイビア)にまとめることにします。これは参照設定 -> 参照の追加 -> Windows 8.1 -> 拡張から追加できます。
作成したビヘイビアの基本部分は以下のようなものです。
このビヘイビアには標準でジェネリック版がないので、Attachしたときに対象のDependencyObjectがScrollViewerか確認した上でAssociatedObjectプロパティに格納し、とりあえずScrollViewerにキャストしたものをAssociatedViewerプロパティから参照できるようにしました。
その下のAssociatedSelectorプロパティの型はSelectorですが、これはListViewやGridViewの基底クラスに当たるものです。なるべく汎用性を持たせようとしたのですが、この記事では関係ないのでListViewのことだと思ってください。
この中のGetFirstDescendantOfType<T>メソッドは
WinRT XAML Toolkit のVisualTreeHelperExtensions.GetFirstDescendantOfType<T>拡張メソッドです。これは子孫の中から指定された型の最初のものを取得するので、このプロパティからScrollViewer内にあるListViewを参照できます。
その下のCompositeDisposableは、イベント処理をReactive Extensionsでやるので、その後始末のためです。
また、この記事では直接触れませんが、方針として子コントロールをCanvas内に配置する座標を計算する際、ScrollViewerのサイズを基準にします。これに合わせるため起動時にScrollViewerとListViewのCanvasのサイズを揃えることとし(1倍の状態)、ScrollViewerからの座標の入力があればCanvas内の座標に変換し、さらに1倍のときの座標に変換したものを基準にします。でないと座標を間違えずに取り扱える気がしないので。
それでは、初めに処理の土台となるヘルパーメソッドを作ります。
計算を簡単にするため起動時にScrollViewerとListViewのCanvasのサイズを揃える前提で、ズームしたときの変化とScrollViewerのプロパティの関係を模式化したのが以下です。
ズームインすることによってCanvasの仮想的なサイズが拡大し、Canvasの位置(左上角)とScrollViewerの位置(左上角)がずれます。これからScrollViewer内の任意の座標をCanvas内の座標に変換するには、CanvasのScrollViewerに対する相対座標の値を加えればいいことが分かります。
さらにCanvas内の座標を1倍のときの座標に変換するにはScrollViewerの倍率で割ればいいので、ScrollViewer内の座標をCanvasの1倍のときの座標に変換するメソッドは以下のようになります。引数のinViewerPositionがScrollViewer内の座標、viewerZoomFactorがScrollViewerの倍率です。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private Point ConvertToInSelectorPosition(Point inViewerPosition, float viewerZoomFactor)
{
var selectorPosition = AssociatedSelector.TransformToVisual(AssociatedViewer).TransformPoint(default(Point));
var offsetX = (inViewerPosition.X - selectorPosition.X) / viewerZoomFactor;
var offsetY = (inViewerPosition.Y - selectorPosition.Y) / viewerZoomFactor;
return new Point(offsetX, offsetY);
}
selectorPositionはCanvasのScrollViewerに対する相対座標で(負の値になる)、それとScrollViewer内の座標を合計した上で倍率で割っています。
逆に、ScrollViewer内の座標とCanvas内の1倍のときの座標がScrollViewerのある倍率のときに一致するようScrollViewerを操作するメソッドは以下のようになります。引数のinSelectorPositionがCanvas内の座標です。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void RestoreInViewerPosition(Point inViewerPosition, Point inSelectorPosition, float viewerZoomFactor)
{
var offsetX = inSelectorPosition.X * viewerZoomFactor - inViewerPosition.X;
var offsetY = inSelectorPosition.Y * viewerZoomFactor - inViewerPosition.Y;
AssociatedViewer.ChangeView(offsetX, offsetY, viewerZoomFactor);
}
ScrollViewer.ChangeView メソッドは水平と垂直の両スクロール量(オフセット)、倍率を一元的に操作するメソッドです。Windows 8.1で入ったメソッドで、従来のバラバラだったメソッドを置き換えるものです。
座標の計算はConvertToInSelectorPositionメソッドの逆になっているのが分かると思います。という意味で対になるメソッドです。
[追記]
ConvertToInSelectorPositionメソッドについて、CanvasとScrollViewerの相対座標の値はScrollViewerのHorizontalOffsetとVerticalOffsetに一致するから、わざわざメソッドを使って取得する必要はないのではと思った方もいるかもしれません。メソッドにするとこんな感じです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private Point ConvertToInSelectorPositionAlternative(Point inViewerPosition, float viewerZoomFactor)
{
var offsetX = (inViewerPosition.X + AssociatedViewer.HorizontalOffset) / viewerZoomFactor;
var offsetY = (inViewerPosition.Y + AssociatedViewer.VerticalOffset) / viewerZoomFactor;
return new Point(offsetX, offsetY);
}
そうしなかった理由は自分でも忘れてましたが、この方法は倍率が1より小さくなる、すなわちCanvasがScrollViewerより小さくなったときは無力になるからです。HorizontalOffsetとVerticalOffsetは0より小さくならないので。
と言いつつ、倍率の最小値を1に制限してしまえば問題にはならないので、これでも行けるんですけどね。
2.3. ズームできるようにする
ようやくズームですが、WinRTのScrollViewerの場合、ZoomModeをEnabledにするだけでタッチのピンチ/ムーブが可能になります。したがって、以下はマウスでこれをやるためのものです(タッチも受け付けますが)。
なお、ズームといっても中心点を固定して拡大/縮小する形式と、ズームイン/ズームアウトのモードを決めて任意の点をクリックするとその点を中心に拡大/縮小する形式がありますが、UI的に後者の方が優れていると思うので、そちらで行きます。
ということで、ズームイン/ズームアウトのモードを示すenumを用意しました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum ZoomDirectionMode
{
None = 0,
ZoomIn,
ZoomOut,
}
このモード設定は他に任せ、このビヘイビアにはこの型のZoomDirection依存関係プロパティを置き、PageのViewModelとバインドして現在の設定を受け取れるようにします。
その上でScrollViewerのTappedイベントをRxで購読するメソッドを作り、ビヘイビアのOnLoadedメソッドで実行します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void StartListenTap()
{
disposer.Add(
Observable.FromEventPattern<TappedEventHandler, TappedRoutedEventArgs>(
h => h.Invoke,
h => AssociatedViewer.Tapped += h,
h => AssociatedViewer.Tapped -= h)
.Subscribe(x => OnTapped(x.Sender, x.EventArgs)));
}
Tappedイベントが来たときに処理するメソッドは以下のとおりです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void OnTapped(object sender, TappedRoutedEventArgs e)
{
var inViewerPosition = e.GetPosition((FrameworkElement)sender);
var inSelectorPosition = ConvertToInSelectorPosition(inViewerPosition, AssociatedViewer.ZoomFactor);
switch (ZoomDirection)
{
case ZoomDirectionMode.ZoomIn:
e.Handled = true;
ZoomIn(inViewerPosition, inSelectorPosition);
break;
case ZoomDirectionMode.ZoomOut:
e.Handled = true;
ZoomOut(inViewerPosition, inSelectorPosition);
break;
}
}
private const double zoomNotchFactor = 0.18F;
private void ZoomIn(Point inViewerPosition, Point inSelectorPosition)
{
var factor = Math.Min(9F, AssociatedViewer.ZoomFactor * (float)(1D + zoomNotchFactor));
RestoreInViewerPosition(inViewerPosition, inSelectorPosition, factor);
}
private void ZoomOut(Point inViewerPosition, Point inSelectorPosition)
{
var factor = Math.Max(1F, AssociatedViewer.ZoomFactor / (float)(1D + zoomNotchFactor));
RestoreInViewerPosition(inViewerPosition, inSelectorPosition, factor);
}
まずScrollViewer内の座標とCanvas内の1倍のときの座標を取得し、ZoomDirectionに従って振り分けます。zoomNotchFactorは1回の操作で変える倍率の刻みです。倍率は最小1倍、最大9倍でリミットをかけています。
面倒な計算はヘルパーメソッドに任せているので、こんなものです。
2.4. ムーブできるようにする
ムーブもイベントをRxで購読すればいいわけですが、これには二通りあります。
Manipulationイベント: ManinulationStartedで開始、ManipulationDeltaで移動、ManipulationCompletedで終了。
Pointerイベント: PointerPressedで開始、PointerMovedで移動、PointerReleasedなどで終了。
どちらでも行けますが、まずManipulationの方から。イベントを購読するメソッドは以下のようなものです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void StartListenManipulation()
{
var manipulationStarted = Observable.FromEvent<ManipulationStartedEventHandler, ManipulationStartedRoutedEventArgs>(
h => (sender, e) => h(e),
h => AssociatedViewer.ManipulationStarted += h,
h => AssociatedViewer.ManipulationStarted -= h)
.Where(e => e.PointerDeviceType == PointerDeviceType.Mouse);
var manipulationDelta = Observable.FromEvent<ManipulationDeltaEventHandler, ManipulationDeltaRoutedEventArgs>(
h => (sender, e) => h(e),
h => AssociatedViewer.ManipulationDelta += h,
h => AssociatedViewer.ManipulationDelta -= h);
var manipulationCompleted = Observable.FromEvent<ManipulationCompletedEventHandler, ManipulationCompletedRoutedEventArgs>(
h => (sender, e) => h(e),
h => AssociatedViewer.ManipulationCompleted += h,
h => AssociatedViewer.ManipulationCompleted -= h);
disposer.Add(manipulationDelta
.SkipUntil(manipulationStarted.Do(e => OnManipulationStarted(e)))
.TakeUntil(manipulationCompleted.Do(e => OnManipulationCompleted(e)))
.Throttle(TimeSpan.FromMilliseconds(10)) // 10 msec throttling
.ObserveOn(SynchronizationContext.Current)
.Repeat()
.Subscribe(e => OnManipulationDelta(e)));
}
移動量を捉えるだけならManipulationDeltaだけでいいですが、開始位置を保存しておくのと入力がマウスかどうか判別するにはManipulationStartedRoutedEventArgsを見る必要があるので、ManipulationStartedが必要になります。一方、移動が終わればManipulationDeltaも止まるので、ManipulationCompletedには実質的な意味はありません。
これらを受けた処理をするメソッドです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private Point startPosition;
private double startHorizontalOffset;
private double startVerticalOffset;
private float startZoomFactor;
private void OnManipulationStarted(ManipulationStartedRoutedEventArgs e)
{
e.Handled = true;
startPosition = e.Position;
startHorizontalOffset = AssociatedViewer.HorizontalOffset;
startVerticalOffset = AssociatedViewer.VerticalOffset;
startZoomFactor = AssociatedViewer.ZoomFactor;
}
private void OnManipulationCompleted(ManipulationCompletedRoutedEventArgs e)
{
e.Handled = true;
}
private void OnManipulationDelta(ManipulationDeltaRoutedEventArgs e)
{
e.Handled = true;
float? factor = null;
var offsetX = startHorizontalOffset - e.Cumulative.Translation.X;
var offsetY = startVerticalOffset - e.Cumulative.Translation.Y;
var currentScale = e.Cumulative.Scale;
if (currentScale != 1F)
{
factor = startZoomFactor * currentScale;
offsetX = offsetX * currentScale + startPosition.X * (currentScale - 1F);
offsetY = offsetY * currentScale + startPosition.Y * (currentScale - 1F);
}
AssociatedViewer.ChangeView(offsetX, offsetY, factor);
}
開始時にその時点の状態を保存しておき、移動時に(スロットリングで間隔を挟みつつ)開始時からの累積量を加え、ScrollViewer.ChangeViewメソッドで反映させています。一応倍率(Scale)の変化も加えるようにしていますが、無駄かもしれません。
次にPointerの方を。こちらは少し注意が必要です。
第一に、PointerMovedイベントはカーソルが上を動いているときは常に発生しているので、区切るために開始時と終了時のイベントが必須ですが、終了時のイベントがItemsControlを囲んだScrollViewerでは返ってこないので(自分で試した結果)、ListViewの方でイベントを購読する必要があります。
第二に、終了時のイベントが何になるのか明示されていません。
MSDN には「PointerReleasedの代わりの他のイベントが、アクション — たとえば、PointerCanceledまたはPointerCaptureLostの最後に発生する場合があります。常にペアで発生するPointerPressedおよびPointerReleasedイベントに依存しないでください。」とあり、PointerReleasedだけではダメなのは分かりますが、PointerCanceledとPointerCaptureLostも例示に過ぎないので、完全に止められる保証がありません。
ともあれ、イベントを購読するメソッドは以下のようなものです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void StartListenPointer()
{
var pointerPressed = Observable.FromEvent<PointerEventHandler, PointerRoutedEventArgs>(
h => (sender, e) => h(e),
h => AssociatedSelector.PointerPressed += h,
h => AssociatedSelector.PointerPressed -= h)
.Where(e => e.Pointer.PointerDeviceType == PointerDeviceType.Mouse);
var pointerMoved = Observable.FromEvent<PointerEventHandler, PointerRoutedEventArgs>(
h => (sender, e) => h(e),
h => AssociatedSelector.PointerMoved += h,
h => AssociatedSelector.PointerMoved -= h);
var pointerUnpressed = Observable.Merge(
Observable.FromEvent<PointerEventHandler, PointerRoutedEventArgs>(
h => (sender, e) => h(e),
h => AssociatedSelector.PointerReleased += h,
h => AssociatedSelector.PointerReleased -= h),
Observable.FromEvent<PointerEventHandler, PointerRoutedEventArgs>(
h => (sender, e) => h(e),
h => AssociatedSelector.PointerCanceled += h,
h => AssociatedSelector.PointerCanceled -= h),
Observable.FromEvent<PointerEventHandler, PointerRoutedEventArgs>(
h => (sender, e) => h(e),
h => AssociatedSelector.PointerCaptureLost += h,
h => AssociatedSelector.PointerCaptureLost -= h));
disposer.Add(pointerMoved
.SkipUntil(pointerPressed.Do(e => OnPointerPressed(e)))
.TakeUntil(pointerUnpressed.Do(e => OnPointerUnpressed(e)))
.Throttle(TimeSpan.FromMilliseconds(10)) // 10 msec throttling
.ObserveOn(SynchronizationContext.Current)
.Repeat()
.Subscribe(e => OnPointerMoved(e)));
}
終了時はPointerReleasedとPointerCanceledとPointerCaptureLostをまとめて購読する形です。保険のためにPointerExitedを追加してもいいかもしれません。
これらを受けたメソッドです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private double startHorizontalOffsetPosition;
private double startVerticalOffsetPosition;
private void OnPointerPressed(PointerRoutedEventArgs e)
{
e.Handled = true;
var startPosition = e.GetCurrentPoint(AssociatedViewer).Position;
startHorizontalOffsetPosition = AssociatedViewer.HorizontalOffset + startPosition.X;
startVerticalOffsetPosition = AssociatedViewer.VerticalOffset + startPosition.Y;
}
private void OnPointerUnpressed(PointerRoutedEventArgs e)
{
e.Handled = true;
}
private void OnPointerMoved(PointerRoutedEventArgs e)
{
e.Handled = true;
var position = e.GetCurrentPoint(AssociatedViewer).Position;
var offsetX = startHorizontalOffsetPosition - position.X;
var offsetY = startVerticalOffsetPosition - position.Y;
AssociatedViewer.ChangeView(offsetX, offsetY, null);
}
Manipulationの場合とやっていることは大体同じです。これで別に問題は起きなかったのですが、どちらかを選ぶとすればManipulationの方が面倒がないかなという気がします。
2.5. 回転やサイズ変更や終了後の復元ができるようにする
もう少し続きます。
回転への対応はストアアプリならではの要求ですが、このScrollViewerの場合は、今まで見ていたものが回転しても明後日の方に飛んでいかない、言い換えれば中心にあるものは回転しても中心のままにする、と捉えることができます。
これはサイズ変更への対応にも流用できて、アプリの横幅が変更されても中心にあるものは中心に維持される、となります。さらに終了後の復元への対応にも応用できて、終了時に中心にあったもの(と倍率)がそのまま復元される、となります。
したがって、これらは共通の処理で実現でき、違うのはタイミングだけです。このためにはScrollViewerの中心座標に対応するCanvasの1倍のときの座標とScrollViewerの倍率を記録しておいて、それぞれ適当なタイミングで復元すればいいわけです。
まずこの座標を記録するものとしてPoint型のInSelectorCenterPosition依存関係プロパティ、倍率を記録するものとしてFloat型のViewerZoomFactor依存関係プロパティを置きます。これらはPageのViewModelとバインドして変更がある度にLocalSettingsかRoamingSettingsに保存するようにすれば、終了後の復元にも使えます。
これらを記録するメソッドは以下のとおりです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void SaveInViewerCenterPosition()
{
var inViewerCenterPosition = new Point(AssociatedViewer.ActualWidth / 2D, AssociatedViewer.ActualHeight / 2D);
InSelectorCenterPosition = ConvertToInSelectorPosition(inViewerCenterPosition, AssociatedViewer.ZoomFactor);
ViewerZoomFactor = AssociatedViewer.ZoomFactor;
}
復元するメソッドの方は以下のとおりです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void RestoreInViewerCenterPosition()
{
if ((ViewerZoomFactor == 0F) || (InSelectorCenterPosition == default(Point)))
return;
var inViewerCenterPosition = new Point(AssociatedViewer.ActualWidth / 2D, AssociatedViewer.ActualHeight / 2D);
RestoreInViewerPosition(inViewerCenterPosition, InSelectorCenterPosition, ViewerZoomFactor);
}
この記録するタイミングにはScrollViewerのViewChangedイベントが利用できます。これはタッチによる変更も捉えることができます。また、回転とサイズ変更のときに復元するタイミングにはSizeChangedイベントが利用できます(回転で縦横が入れ替わる、すなわちサイズが変わるので)。
これらをRxで購読するにはOnLoadedイベントで以下のようにします。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ViewChanged event
disposer.Add(
Observable.FromEventPattern<ScrollViewerViewChangedEventArgs>(
h => AssociatedViewer.ViewChanged += h,
h => AssociatedViewer.ViewChanged -= h)
.Throttle(TimeSpan.FromMilliseconds(100)) // 100 msec throttling
.ObserveOn(SynchronizationContext.Current)
.Subscribe(e_ => SaveInViewerCenterPosition()));
// SizeChanged event
disposer.Add(
Observable.FromEvent<SizeChangedEventHandler, SizeChangedEventArgs>(
h => (sender_, e_) => h(e_),
h => AssociatedViewer.SizeChanged += h,
h => AssociatedViewer.SizeChanged -= h)
.Subscribe(e_ => RestoreInViewerCenterPosition()));
終了後の復元のときは、起動中の適当なタイミングで復元を実行すればいいわけですが、注意点としてListViewの子コントロールがロードされた後でなければ正しく復元されないので工夫が必要です。
最終的なビヘイビアは
レポジトリ の方で。記事中で取り上げてない部分もありますが。
ScrollViewerのXAMLは以下のようになりました。
表示させるとこんな感じです。
デザインは作り込んでいませんが、フライアウトを付けたりしています。
以上で終わりです。お疲れ様でした。
3. 後書き
実はこの方法は
TokyoSubwayView で使ったものとほぼ同じだったりします。記事の材料にするために見直したりしてきましたが、まだ生煮えの感を免れません。強引にまとめようとすれば出来なくもないかもしれませんが、それがXAML的に正しいかという判断が付かない程度のXAML力でした。
ということで、もうXAML Advent Calendarも後半ですが、引き続き各位の記事で勉強させていただこうと思います。明日は
@icchu さんです。期待してます。