RunningCSharp

MS系開発者による、雑多な記事。記事は所属企業とは関係のない、個人の見解です。

Xamarin:Xamarinで添付プロパティ(Attached Property)を試す

WPFではViewのコントロールに独自の値を渡したり、独自の値の変更を契機にイベントを動かしたい時などに添付プロパティを使っていました。 Xamarinでも使えるようなので、とりあえずシンプルな実装を試してみました。

添付プロパティの実装は以下の通り。

public class Attached
{
    public static readonly BindableProperty TestProperty =
    BindableProperty.CreateAttached("Test", typeof(bool), typeof(Attached), false, propertyChanging: OnTestChanged);

    private static void OnTestChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var editor = bindable as Editor;
        if ((bool)newValue)
        {
            //フォーカスが離れた際にイベント実行
            editor.Unfocused += Editor_Unfocused; ;
        }
        else
        {
            editor.Unfocused -= Editor_Unfocused;
        }
    }

    private static void Editor_Unfocused(object sender, FocusEventArgs e)
    {
        var editor = sender as Editor;
        //テキストを赤に。
        editor.TextColor = Color.Red;
    }
}

添付プロパティの適用個所は以下のような感じで。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="AttachedApp.MainPage"
             xmlns:local="clr-namespace:AttachedApp">
  <Editor local:Attached.Test="True" Text="TestEditor" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

UWPでの動作イメージはこんな感じです。

・起動時

f:id:ys-soniclab:20160815234422p:plain

・テキストボックスからフォーカスが外れた時

f:id:ys-soniclab:20160815234436p:plain

この例ですと、Editorにフォーカスが移ると文字が青くなるだけの簡素な内容ですが、 ViewModelからコマンドを渡してあげたりイベントで使いたい値を渡してあげたり、幅広い用途が考えられそうです。