Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amay077/ca0d9e2a6a260b5ab88561873b37713b to your computer and use it in GitHub Desktop.
Save amay077/ca0d9e2a6a260b5ab88561873b37713b to your computer and use it in GitHub Desktop.
Xamarin Workbooks で、 Entry の文字数8文字以下で Button の IsEnabled を false にする Behavior を作ってみたサンプルです。
uti platform packages
com.xamarin.workbook
iOS
id version
Xamarin.Forms
2.2.0.31

Entry の文字数8文字以下で Button の IsEnabled を false にする Behavior

File > Add Package から[Xamarin.Forms]を追加します。

#r "Xamarin.Forms.Platform.iOS"
#r "Xamarin.Forms.Core"
#r "Xamarin.Forms.Xaml"
#r "Xamarin.Forms.Platform"

自動的に上記が追加されますので、C# コードを追加していきましょう。

using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

「文字列が8文字以下なら指定されたViewをDisableにする」という Entry 用の Behavior を作成します。

class MinLengthToDisableBehavior : Behavior<Entry>
{
    readonly View _otherView;
    public MinLengthToDisableBehavior(View otherView)
    {
        _otherView = otherView;
    }
    
    protected override void OnAttachedTo(Entry bindable) 
    {
        bindable.TextChanged += OnTextChanged;
    }

    protected override void OnDetachingFrom(Entry bindable) 
    {
        bindable.TextChanged -= OnTextChanged;
    }

    private void OnTextChanged(object sender, TextChangedEventArgs e) 
    {
        _otherView.IsEnabled = e.NewTextValue.Length > 8;
    }    
}

Entry と Button を配置、Entry の Bihaviors に、上で作成した MinLengthToDisableBehavior を指定します(button を添えて)

public class SamplePage : ContentPage
{
    public SamplePage()
    {
        var button = new Button 
        { 
            Text = "Push me!",
        };

        var entry = new Entry
        {
            Behaviors = { new MinLengthToDisableBehavior(button) }
        };

        Content = new StackLayout 
        {
            Children = 
            {
                entry,
                button
            }
        };
    }
}
public class App : Application
{
    public App()
    {
        MainPage = new NavigationPage(new SamplePage());
    }
}

Workbooks で実行するには以下のおまじないを追加する必要があります。

Xamarin.Forms.Forms.Init();
var a = new App();
KeyWindow.RootViewController = a.MainPage.CreateViewController();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment