星期四, 8月 03, 2017

[X.Form] IValueConverter - Entry 必填

電子書 Creating Mobile Apps with Xamarin.Forms Book First Edition BindingConverter 章節範例,把 Code 複製下來跑跑看,順道筆記一下

建立 IntToBoolConverter
// 要使用 IValueConverter 要引用該 namespace
using Xamarin.Forms;

namespace DataBindingPractice
{
    public class IntToBoolConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (int)value != 0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (bool)value ? 1 : 0;
        }
    }  
}
xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                xmlns:local="clr-namespace:DataBindingPractice"
                x:Class="DataBindingPractice.XF9_IValueConvert3">

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

    <ContentPage.Content>
        <StackLayout Spacing="20" HorizontalOptions="Center" VerticalOptions="Center">
            <Entry 
                x:Name="entry" 
                FontSize="Large"
                Text=""
                Placeholder="text to enable button" />

            <Button 
                Text="Save or Send (or something)"
                FontSize="Large" 
                HorizontalOptions="Center" 
                IsEnabled="{Binding Source={x:Reference entry}, 
                Path=Text.Length, 
                Converter={StaticResource intToBool}}" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
執行結果-1

[X.Form] IValueConverter - Entry 必填-1

執行結果-2

[X.Form] IValueConverter - Entry 必填-2

沒有留言:

張貼留言