漫坊亭

社会の底辺プログラマ

Caliburn Micro Part 6: Introduction to Screens and Conductors をやってみる。

Mindscape Blog » Blog Archive » Caliburn Micro Part 6: Introduction to Screens and Conductors manbou404.hatenablog.com

要するに、Conductorの使い方。

Step 1: Getting started

Part1のソリューションをつかう。

Step 2: The conductor

ShellViewModelをConductorから継承する。Conductorは、PropertyChangedBaseも含んでいる。

// <ShellViewModel>
using Caliburn.Micro;

namespace Tutorial
{                               // ↓↓↓↓ PropertyChangedBaseから変更 
    public class ShellViewModel : Conductor<object>, IShell
    {
    }
}

今回のサンプルは、1つの領域しか管理しないので、基本的なConductorでよい・・・らしい。

Step 3: The screens

Red / Blue / GreenのViewとViewModelをプロジェクトに追加
(ソースはRedのみ、BlueとGreenも同様に。。。)

// <RedViewModel.cs>
using Caliburn.Micro;

namespace Tutorial
{
    public class RedViewModel : Screen
    {
    }
}
<!--RedView.xaml>
<UserControl x:Class="Tutorial.RedView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
    <Grid>
        <!--             ↓ここと     ここ↓を、Blue, Greenにする-->
        <TextBlock Text="Red" Foreground="Red" FontSize="48" FontWeight="Bold"  
                   VerticalAlignment="Center" HorizontalAlignment="Center" />
    </Grid>
</UserControl>

プロジェクトは、こうなる。
f:id:jfactory:20150629103049p:plain

Step 4: Interactivity

画面上部にボタンを3つ追加する。

<!--ShellView.cs-->
<UserControl x:Class="Tutorial.ShellView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Width="300" Height="300" Background="LightBlue">
    
    <DockPanel Width="300" Height="300" Background="LightBlue">
        <StackPanel Orientation="Horizontal" DockPanel.Dock="Top" HorizontalAlignment="Center">
            <Button x:Name="ShowRedScreen" Content="Red" Width="50" />
            <Button x:Name="ShowGreenScreen" Content="Green" Width="50" Margin="12,0,0,0" />
            <Button x:Name="ShowBlueScreen" Content="Blue" Width="50" Margin="12,0,0,0" />
        </StackPanel>
    </DockPanel>
    
</UserControl>

ボタンハンドラを追加する。

public class ShellViewModel : Conductor<object>, IShell
{
    public void ShowRedScreen()
    {
        this.ActivateItem(new RedViewModel());
    }

    public void ShowGreenScreen()
    {
        this.ActivateItem(new GreenViewModel());
    }

    public void ShowBlueScreen()
    {
        this.ActivateItem(new BlueViewModel());
    }
}

Step 5: displaying the active screen

ShellViewに下記を追加

    <!--省略-->
    <ContentControl x:Name="ActiveItem" />
</DockPanel>

Caliburn.Microにより、ActiveItemが自動的にバインドされる。

f:id:jfactory:20150629104628p:plain

以上!

ソース一式