shuhelohelo’s blog

Xamarin.Forms多めです.

Xamarin.FormsでのValueConverterの使い方

www.c-sharpcorner.com

docs.microsoft.com

IValueConverterを継承したクラスを作り,実装する.

基本的な形は以下のとおり.

    public class HogehogeConverter :IValueConverter
    {
        //Source→View
        //ViewModelやコードビハインドからXaml側へ
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return someReturnValue;
        }

        //View→Source
        //Xaml側からViewModelやコードビハインドへ
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Convert(value, targetType, parameter, culture);
        }
    }

使い方はStaticResourceとして定義して使う方法と,マークアップ拡張として使う方法がある.他にもある.

StaticResourceとして使う.

StaticResourceとしてコンバーターを登録し,Converter={StaticResource intToBool}}"というように使う.

    <ContentPage.Resources>
        <ResourceDictionary>
            <local:IntToBoolConverter x:Key="intToBool" />
        </ResourceDictionary>
    </ContentPage.Resources>


        <Button Text="Search"
                HorizontalOptions="Center"
                VerticalOptions="CenterAndExpand"
                IsEnabled="{Binding Source={x:Reference entry1},
                                    Path=Text.Length,
                                    Converter={StaticResource intToBool}}" />

マークアップ拡張として使う

IMarkupExtensionを追加で実装しておくと,XAML側でStaticResourceとして登録する必要がない.

    public class NullBoolConverter :IMarkupExtension, IValueConverter
    {
        //Source→View
        //ViewModelやコードビハインドからXaml側へ
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return someReturnValue;
        }

        //View→Source
        //Xaml側からViewModelやコードビハインドへ
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Convert(value, targetType, parameter, culture);
        }

        public object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }

XAML側ではクラス名でコンバーターを指定できる.

    IsVisible="{Binding IsLast, Converter={local:NullBoolConverter}}"

マークアップ拡張についてはこちらを参考に.

blog.okazuki.jp

サンプル

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType != typeof(bool))
                throw new ArgumentException();

            bool flag = false;
            if (value != null && value is bool)
            {
                flag = (bool)value;
            }
            return !flag;
        }