question

EduardoGomez-1870 avatar image
0 Votes"
EduardoGomez-1870 asked LeonLu-MSFT commented

enable button on xaml

Hello

I have this VM

  private readonly INavigationService _navigationService;
    
         public UserActivityModel? UserActivity { get; set; }
    
         public UserModel? User { get; set; }
    
         private Dictionary<string, object> Answer { get; set; }
    
         public DelegateCommand MakeAWishCommand { get; set; }
    
         public ActivityWishResponseWishPendingViewModel(
             INavigationService navigationService,
             IPageDialogService pageDialogService,
             IDialogService dialogService,
             IDeviceService deviceService,
             IEventAggregator eventAggregator) : base(navigationService, pageDialogService, dialogService, deviceService, eventAggregator)
         {
             _navigationService = navigationService;
             Answer = new Dictionary<string, object>();
    
             MakeAWishCommand = new DelegateCommand(async () => await MakeAWishAction());
    
             User = LocalEnv.Instance.CurrentSession.User;
         }
    
         public override void OnNavigatedTo(INavigationParameters parameters)
         {
             switch (parameters.GetNavigationMode())
             {
                 case NavigationMode.New:
                     LoadPage(parameters);
    
                     break;
             }
         }
    
         internal async void LoadPage(INavigationParameters parameters)
         {
             if (!parameters.ContainsKey(AppConstants.user_activity_id)) return;
    
             var userActivityId = parameters.GetValue<int>(AppConstants.user_activity_id);
    
             try
             {
                 LocalEnv.Instance.Log.Info("Get information of activity challenge");
    
                 UserActivity = await ActivityApi.GetActivityById(userActivityId);
                 Title = UserActivity.Activity?.Topic?.Name;
             }
             catch (Exception)
             {
                 LocalEnv.Instance.Log.Error($"Error in GetActivityById in the challenge with id {UserActivity?.Id}");
             }
             finally
             {
                 IsBusyList = false;
             }
         }
    
    
         private Task MakeAWishAction()
         {
             throw new NotImplementedException();
         }
     }
 }

This VM is associated with this XAML

 <Frame
             Grid.Row="1"
             Grid.ColumnSpan="2"
             Padding="0"
             BackgroundColor="{x:StaticResource BackgroundColorThemeDark}"
             CornerRadius="20"
             IsClippedToBounds="True">
             <renderers:CustomEditor
                 AutoSize="TextChanges"
                 HorizontalOptions="FillAndExpand"
                 VerticalOptions="FillAndExpand" />
         </Frame>
    
         <Button
             Grid.Row="2"
             Grid.ColumnSpan="3"
             Margin="100"
             BackgroundColor="{StaticResource PrimaryDark}"
             Command="{Binding MakeAWishCommand}"
             HorizontalOptions="Center"
             IsEnabled="{Binding EnableButton}"
             Style="{StaticResource ButtonCornerBase}"
             Text="{i18N:Translate Send}"
             VerticalOptions="EndAndExpand" />

As you can see, I have an Editor inside a frame, what I am trying to do, is to enable the button when the Editor text inside.

I have a view model base, that implements the InotifyPropertyChanged, And I am also using Fody, so I don't have to do a full property

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

LeonLu-MSFT avatar image
0 Votes"
LeonLu-MSFT answered LeonLu-MSFT commented

Hello,​

Welcome to our Microsoft Q&A platform!

If you want to achieve result: If have text in the Editor, Button is enabled, If the text is empty in the Editor, Button is disabled.

124410-image.png 124541-image.png

And Is your renderers:CustomEditor a custom Editor? If so, you do not need add IsEnabled="{Binding EnableButton}" to Button.

You can achieve it by Xamarin.Forms Binding Value Converters .

Step 1: create a class called IntToBoolConverter.cs

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;
        }
    }


Then add following code to xaml

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


Add reference bettween Button and Editor In the end, I do not have code about renderers:CustomEditor, I use Editor to make a test.

<?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:BtnEnableDemo"
             x:Class="BtnEnableDemo.MainPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:IntToBoolConverter x:Key="intToBool" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <StackLayout>
        <Frame
             Grid.Row="1"
             Grid.ColumnSpan="2"
             Padding="0"
           
             CornerRadius="20"
             IsClippedToBounds="True">
            <Editor
                x:Name="Editor1"
                Text=""
                 AutoSize="TextChanges"
                 HorizontalOptions="FillAndExpand"
                 VerticalOptions="FillAndExpand" />
        </Frame>

        <Button
             Grid.Row="2"
             Grid.ColumnSpan="3"
            
             IsEnabled="{Binding Source={x:Reference Editor1},
                                    Path=Text.Length,
                                    Converter={StaticResource intToBool}}"
             Command="{Binding MakeAWishCommand}"
             HorizontalOptions="Center"
            
            
             Text="Send"
             VerticalOptions="StartAndExpand" />
    </StackLayout>

</ContentPage>



Best Regards,

Leon Lu



If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.



image.png (13.5 KiB)
image.png (13.8 KiB)
· 9
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I try is but by default is enable on my end

124637-capture.png

     <renderers:CustomEditor
                 x:Name="MakeWishEditor"
                 AutoSize="TextChanges"
                 Keyboard="Chat"
                 Placeholder="{i18N:Translate EnterYourAnswer}"
                 Style="{x:StaticResource EditorEditorRadius}"
                 Text=""
                 TextColor="White" />
    
         </Frame>
    
         <Button
             Grid.Row="2"
             Grid.ColumnSpan="3"
             Margin="100"
             BackgroundColor="{x:StaticResource PrimaryDark}"
             Command="{x:Binding MakeAWishCommand}"
             HorizontalOptions="Center"
             IsEnabled="{x:Binding Source={x:Reference MakeWishEditor},
                                   Path=Text.Length,
                                   Converter={x:StaticResource intToBool}}"
             Style="{x:StaticResource ButtonCornerBase}"
             Text="{i18N:Translate Send}"
             VerticalOptions="CenterAndExpand" />

But then if I a type a character and erase it will be False and that is what I want, but by default it should be false



0 Votes 0 ·
capture.png (71.2 KiB)

Hello

This is my Android implementation

 [assembly: ExportRenderer(typeof(CustomEditor), typeof(CustomEditorRenderer))]
 namespace wefeel.Droid.Renderers
 {
     public class CustomEditorRenderer : EditorRenderer
     {
         public CustomEditorRenderer(Context context) : base(context)
         {
    
         }
    
         protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
         {
             base.OnElementChanged(e);
    
             if (Control != null)
             {
                 Control.Background = null;
                 Control.SetBackgroundColor(Android.Graphics.Color.Transparent);
             }
         }
     }

IOS

 [assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEditorRenderer))]
 namespace wefeel.iOS.Renderers
 {
     class CustomEditorRenderer : EntryRenderer
     {
         protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
         {
             base.OnElementChanged(e);
    
             if (Control != null)
             {
                 Control.BorderStyle = UITextBorderStyle.None;
             }
         }
     }
 }



0 Votes 0 ·

Great, thanks for your sharing.

0 Votes 0 ·
Show more comments