3
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DataTemplateを使う時に覚えておきたい。親ViewのViewModelをRelativeSourceで直接バインディング

Last updated at Posted at 2015-08-18

はじめに

WPFの画面遷移の基本は、ContentControlとDataTemplateの組み合わせによるViewの切り替えです。
非常に強力な機構なのですが、データ型(ViewModelクラスの種別)によって、Viewが切り替わるというルールなので、DataTemplateが参照している(DataContextに格納されている)ViewModelは、データクラスとなります。
ContentControlの想定している利用ケースが、データを全て持ったViewModelであり多くの場合は、この方が都合が良いのですが、画面の一部分を切り替えるような画面遷移にContentControlを利用した場合に、不都合が生じる場合があります。
DataTemplateバインディング.jpg
不都合といっても単純に、親のViewが持っているViewModelをDataTemplateの参照しているViewModelへコピーする手間がかかるという程度の話なのですが、表示するだけではなく値を永続化する場合には、厄介なことになります。

親ViewのViewModelをバインディングする

WPFのバインディング機構を熟知されている方なら当然のテクニックなのですが、RelativeSourceで親Viewに対してバインディングを行う事ができます。
独特な書き方なので、暗記するかメモして利用するといいでしょう。

Test.xaml
<Slider Width="100"
        Height="16"
        Maximum="2"
        Minimum="0.1"
        Value="{Binding DataContext.ZoomValue,
                RelativeSource={RelativeSource FindAncestor,
                AncestorType={x:Type view:ParentView}}, Mode=TwoWay}" />

バインディングの書式は、色々とあるのですが、ContentControlが複数階層になっていても大丈夫な親Viewを直接検索する方法が、最も単純で簡単な方法です。

3
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?