タブを追加/削除する
切り替えられるコンテンツの数は固定であることもありますが、変化することもあります。ここでは、ContentViewModel を用いたタブの追加/削除方法について紹介します。
まず、タブが追加されるということは、TabControl コントロールの ItemsSource プロパティに指定されているコレクションの数が増えるということです。つまり、コレクションを保持している MainViewModel で、新たな ContentViewModel をコレクションに追加することで実現できます。
そういうわけで、MainViewModel に AddContentCommand を追加します。
namespace Tips_TabControl.ViewModels
{
using System.Collections.ObjectModel;
public class MainViewModel : NotificationObject
{
private ObservableCollection<ContentViewModel> _contents = new ObservableCollection<ContentViewModel>();
/// <summary>
/// コンテンツのコレクションを取得します。
/// </summary>
public ObservableCollection<ContentViewModel> Contents
{
get { return this._contents; }
}
private DelegateCommand _addContentCommand;
/// <summary>
/// コンテンツ追加コマンドを取得します。
/// </summary>
public DelegateCommand AddContentCommand
{
get
{
return this._addContentCommand ?? (this._addContentCommand = new DelegateCommand(
_ =>
{
var content = new ContentViewModel("Item" + _count);
_count++;
this.Contents.Add(content);
},
_ => this.Contents.Count < 4));
}
}
private int _count;
}
}
追加されるコンテンツの違いがわかるように、Title プロパティにカウンタの数値を含めます。また、実行条件として、コレクションの数を 4 個までとし、それ以上は追加できなくなるようにしています。
このコマンドを使用してコンテンツが追加できるように View のほうも変更します。
<Window x:Class="Tips_TabControl.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainView" Height="300" Width="300">
<DockPanel>
<Button DockPanel.Dock="Top" Content="Add" Command="{Binding AddContentCommand}" />
<TabControl ItemsSource="{Binding Contents}" SelectedIndex="0">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title, StringFormat={}これは{0}のコンテンツです。}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</DockPanel>
</Window>
次に、タブを削除する方法を紹介します。タブを削除するということは、MainViewModel が保持しているコレクションの数を減らすということになります。ここでは、タブのヘッダ部に表示される閉じるボタンを押すことで削除するという実装方法を説明します。
タブのヘッダ部に表示するボタンは、ContentViewModel が DataContext になります。したがって、ContentViewModel の中になんらかのコマンドを実装する必要があります。そして、そのコマンドを起点として、MainViewModel のコレクションから該当するアイテムを削除しなくてはなりません。ここでは、ContentViewModel にあるイベントを定義して、それを MainViewModel が購読することでこの一連の動作を実現します。
namespace Tips_TabControl.ViewModels
{
using System;
public class ContentViewModel : NotificationObject, IDisposable
{
/// <summary>
/// 新しいインスタンスを生成します。
/// </summary>
/// <param name="title">タイトルを指定します。</param>
public ContentViewModel(string title)
{
this.Title = title;
}
private string _title;
/// <summary>
/// タイトルを取得します。
/// </summary>
public string Title
{
get { return this._title; }
private set { SetProperty(ref this._title, value); }
}
private DelegateCommand _closeCommand;
/// <summary>
/// 閉じるコマンドを取得します。
/// </summary>
public DelegateCommand CloseCommand
{
get
{
return this._closeCommand ?? (this._closeCommand = new DelegateCommand(_ =>
{
Dispose();
RaiseClosed();
}));
}
}
/// <summary>
/// 閉じたときに発生します。
/// </summary>
public event EventHandler<EventArgs> Closed;
/// <summary>
/// Closed イベントを発行します。
/// </summary>
private void RaiseClosed()
{
var h = this.Closed;
if (h != null)
h(this, EventArgs.Empty);
}
#region IDisposable のメンバ
/// <summary>
/// リソースの破棄をおこないます。
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// アンマネージリソースの破棄をおこないます。
/// マネージリソースも同時に破棄できます。
/// </summary>
/// <param name="disposing">マネージリソースも破棄する場合に true を指定します。</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// 管理 (managed) リソースの破棄処理をここに記述します。
}
// 非管理 (unmanaged) リソースの破棄処理をここに記述します。
}
/// <summary>
/// デストラクタ
/// </summary>
~ContentViewModel()
{
Dispose(false);
}
#endregion IDisposable のメンバ
}
}
Closed イベントを定義し、CloseCommand が実行されたときにこのイベントを発行します。このとき、例えば閉じられた後はもう用済みとなる場合には、保持していたリソースを破棄しておく必要があるため、IDisposable インターフェースを実装し、Dispose() メソッドをコールするようにしています。
ContentViewModel に Closed イベントを定義したので、これを MainViewModel が購読し、発行されたときにコレクションから除外する必要があります。
namespace Tips_TabControl.ViewModels
{
using System;
using System.Collections.ObjectModel;
public class MainViewModel : NotificationObject
{
private ObservableCollection<ContentViewModel> _contents = new ObservableCollection<ContentViewModel>();
/// <summary>
/// コンテンツのコレクションを取得します。
/// </summary>
public ObservableCollection<ContentViewModel> Contents
{
get { return this._contents; }
}
private DelegateCommand _addContentCommand;
/// <summary>
/// コンテンツ追加コマンドを取得します。
/// </summary>
public DelegateCommand AddContentCommand
{
get
{
return this._addContentCommand ?? (this._addContentCommand = new DelegateCommand(
_ =>
{
var content = new ContentViewModel("Item" + _count);
_count++;
content.Closed += OnContentClosed;
this.Contents.Add(content);
},
_ => this.Contents.Count < 4));
}
}
/// <summary>
/// ContentViewModel の Closed イベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private void OnContentClosed(object sender, EventArgs e)
{
var content = sender as ContentViewModel;
if (content == null)
throw new Exception("ContentViewModel 以外から飛んでくることはあり得ない。");
content.Closed -= OnContentClosed;
this.Contents.Remove(content);
}
private int _count;
}
}
AddContentCommand によってコンテンツを追加するときに Closed イベントを購読することで、すべてのコレクション要素の Closed イベントにイベントハンドラを登録させます。
イベントハンドラ内では、どの要素から発生したイベントなのかを入力引数である sender 変数をアンボックス化することで調べることができます。
閉じるボタンを実装した View は次のように記述します。
<Window x:Class="Tips_TabControl.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainView" Height="300" Width="300">
<DockPanel>
<Button DockPanel.Dock="Top" Content="Add" Command="{Binding AddContentCommand}" />
<TabControl ItemsSource="{Binding Contents}" SelectedIndex="0">
<TabControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" VerticalAlignment="Center" />
<Button Content="x" Command="{Binding CloseCommand}" />
</StackPanel>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title, StringFormat={}これは{0}のコンテンツです。}" />
</DataTemplate>
</TabControl.ContentTemplate>
<TabControl.Style>
<Style TargetType="TabControl" BasedOn="{StaticResource {x:Type TabControl}}">
<Style.Triggers>
<DataTrigger Binding="{Binding Contents.Count}" Value="0">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</TabControl.Style>
</TabControl>
</DockPanel>
</Window>
Tweet