LoginSignup
3
2

More than 5 years have passed since last update.

データバインディングを使ってUIとUIを結びつける その2 BooleanToVisibilityConverter編

Last updated at Posted at 2016-03-04

トグルボタンを使ってUIの表示状態を切り替えてみる。
大体のUIはVisibilityというプロパティで管理されている。
Visible, Collapsedの二つの状態を取る。

一方でトグルボタンをクリックするとIsCheckedというプロパティの状態がTrue, False1と切り替わるのだが、
これをそのままx:Bindしようとするとコンパイラに怒られる。

MainPage.Xaml
<Page
    ...
    mc:Ignorable="d">

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Visibility="{x:Bind toggleButton.IsChecked, Mode=OneWay}" HorizontalAlignment="Center" FontSize="32" Text="Show"/>
        <ToggleButton x:Name="toggleButton" Content="Change" FontSize="32" HorizontalAlignment="Center" />
    </StackPanel>
</Page>

error.gif

型が違うので当然だがこのままでは困るので、それを変換してくれるコンバーターを登録する。

まずはこのクラスをプロジェクトに追加する。
これがコンバーターだ。

boolean2visibilityconverter.cs
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;

namespace BindToCollectionData
{
    /// <summary>
    /// BooleanをVisibilityに変換する。
    /// </summary>
    public class Boolean2VisibilityConverter : IValueConverter
    {
        /// <summary>
        /// Trueをセットした場合、変換を逆転させる。TrueがCollapsedを返す。
        /// </summary>
        public bool IsReversed { get; set; }

        public object Convert(object value, Type typeName, object parameter, string language)
        {
            var val = System.Convert.ToBoolean(value);
            if (this.IsReversed)
            {
                val = !val;
            }
            if (val)
            {
                return Visibility.Visible;
            }
            return Visibility.Collapsed;
        }
        public object ConvertBack(object value, Type typeName, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}

コンバーターはIValueConverterインターフェースを継承し、
ConvertConvertBackを実装してあげればいいようだ。
よくわからないので変換部分だけ修正していけばいいだろう。

そしてApp.xamlファイルに修正を加える。<Application.Resources>以下が追加されている。

App.xaml

<Application
    x:Class="BindToCollectionData.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:BindToCollectionData"
    RequestedTheme="Dark">

    <Application.Resources>
        <local:Boolean2VisibilityConverter x:Key="True2Visibility" IsReversed="False"/>
        <local:Boolean2VisibilityConverter x:Key="False2Visibility" IsReversed="True"/>
    </Application.Resources>

</Application>

Boolean2VisibilityConverterx:Keyを割り当ててやることでこの名前で利用できるようになる。
publicなフィールドやプロパティがある場合は
IsReversed="True"のように指定してコンバーターの動作状態を変更したりできる。

もしもコンバーターをCommonフォルダなどにまとめていた場合(今回はプロジェクト名MyProjectとして)Applicationタグに
xmlns:hogehoge="MyProject.Common"のようにXML名前空間2を宣言し、
<hogehoge:Boolean2VisibilityConverter x:Key="...と宣言しないといけないようだ。

そしてx:Bindだ。Converter={StaticResource True2Visibility},という記述を追加している。

MainPage.xaml

<Page
    x:Class="BindToCollectionData.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:BindToCollectionData"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="Show" Visibility="{x:Bind toggleButton.IsChecked, Converter={StaticResource True2Visibility}, Mode=OneWay}" HorizontalAlignment="Center" FontSize="32" />
        <ToggleButton x:Name="toggleButton" Content="Change" FontSize="32" HorizontalAlignment="Center" />
    </StackPanel>
</Page>

これを実行して、ボタンを押すとこんな風にボタンの状態に合わせてUIの表示状態が切り替わる。

hidden.gif

show.gif

少し応用してハンバーガーボタン(ToggleButtonを使ったもの)とSplitViewを組み合わせればメニューを開閉するアプリが作れるようになる。3


どうもWindows8の頃はCommonフォルダ4内にBooleanToVisibilityConverter.csというズバリそのものが存在していたようだが、今はないらしい。

Windows 8.1のストアアプリのテンプレートの構造
http://blog.okazuki.jp/entry/2013/09/21/224812


参考:A BooleanToVisibilityConverter for WinRT
http://blogs.u2u.be/diederik/post/2011/11/14/null.aspx
Thank you Diederik.

データ バインディングの概要
https://msdn.microsoft.com/ja-jp/library/windows/apps/xaml/mt269383.aspx



  1. 正確にはTrue, False, nullの三つの状態を取るNullable<Boolean>型(boolean型ではない)というよくわからないもののようだ。 

  2. https://msdn.microsoft.com/ja-jp/library/windows/apps/xaml/mt185594.aspx 

  3. あとでハンバーガーボタンの例を作って置きたい。 

  4. ストアアプリテンプレートを使って作成を開始した場合、Commonフォルダ内には便利グッズ、もといヘルパークラスやコンバーターが入っていたようだ。なんでUWPのテンプレートにはないの…? 

3
2
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
2