Prism コードサンプル学習:16-RegionContext
はじめに
以下の記事の続きです。
https://qiita.com/mngreen/items/c56d4d327850ca8ef2af
16-RegionContext
本サンプルは、RegionManager.RegionNameを用いてコントロールを割り当てたときに、その挿入したコントロールのDataContextに対してバインディングを行うためにRegionContextを用いている例です。
実際にRegionManager.RegionContextを利用している箇所は以下です。
<UserControl x:Class="ModuleA.Views.PersonList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True">
<Grid x:Name="LayoutRoot" Background="White" Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox x:Name="_listOfPeople" ItemsSource="{Binding People}"/>
<ContentControl Grid.Row="1" Margin="10"
prism:RegionManager.RegionName="PersonDetailsRegion"
prism:RegionManager.RegionContext="{Binding SelectedItem, ElementName=_listOfPeople}"/>
</Grid>
</UserControl>
(実際に動作確認したところ、RegionNameで割り当たったContextに対して、通常通りDataContext={Binding SelectedItem, ElementName=_listOfPeople}としてもバインディングできませんでした。)
RegionManager.RegionContextプロパティは添付プロパティで、アタッチされるとコールバックメソッドであるOnRegionContextChangedメソッドを実行します。
その後の流れがつかめきれなかったのですが、サンプルを例にとると、いったんContentControlが保持し、PersonDetailコントロールを割り当てなおすときにBehaviorでそのオブジェクトを渡しているようでした。
おそらくその役目はBindRegionContextToDependencyObjectBehaviorが担っていると思われます(正直繋がりがよくわかっていません)。
おわりに
今回は、RegionContextについての使い方とそのコードの裏にあるものを自分なりに読み解いてみました。RegionManagerというstaticクラスをFacadeにすることでユーザーに何の意識もさせず、DataContextの情報を送受するためにBehaviorをうまいこと利用している点が上手い仕組みになっているなと感じました。
次回、17-BasicRegionNavigationについて見ていこうと思います。