Hide/Unhide Button based on Condition in C#

I’m working in Xamarin.Forms. In CredentialPage.xml Page, there is a Button, which I want to Hide & Unhide, based on Status of Credentials in CredentialViewMode.cs Page.

CredentialPage.xml

<Button x:Name="Button_Round"
WidthRequest="40"
HeightRequest="40"
CornerRadius="20"
BorderWidth="2"
TextColor="White"
BorderColor="Teal"
BackgroundColor="Teal"
Text="Accept Offer"
Command="{Binding ProcessOffer}" />

CredentialViewModel.cs
#region Bindable Command
[Obsolete]
public ICommand ProcessOffer => new Command(async () =>
{
    var RegisteredPIN = await SecureStorage.GetAsync("RegisteredPIN");
    string PIN = await App.Current.MainPage.DisplayPromptAsync("Enter PIN", null, "Ok", "Cancel", null, 6, Keyboard.Numeric);
    if (PIN == RegisteredPIN)
    {
        try
        {
            //await _poolConfigurator.ConfigurePoolsAsync();
            var agentContext = await _agentContextProvider.GetContextAsync();
            var credentialRecord = await _credentialService.GetAsync(agentContext, _credential.Id);
            var connectionId = credentialRecord.ConnectionId;
            var connectionRecord = await _connectionService.GetAsync(agentContext, connectionId);
            (var request, _) = await _credentialService.CreateRequestAsync(agentContext, _credential.Id);
            await _messageService.SendAsync(agentContext.Wallet, request, connectionRecord);
            await DialogService.AlertAsync("Request has been sent to the issuer.", "Success", "Ok");
        }
        catch (Exception e)
        {
            await DialogService.AlertAsync(e.Message, "Error", "Ok");
        }
    }
    else if (PIN != RegisteredPIN && PIN != null)
    {
        DialogService.Alert("Provided PIN is not correct");
    }
});

#endregion

Condition on which I want to Hide/Unhide the Button
if(_credentialStatus == "Offered")
{
    // Button should be Visible
}
else
{
    // Hide the Button
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use the IsVisible property:

<Button x:Name="Button_Round"
WidthRequest="40"
HeightRequest="40"
CornerRadius="20"
BorderWidth="2"
TextColor="White"
BorderColor="Teal"
BackgroundColor="Teal"
Text="Accept Offer"
Command="{Binding ProcessOffer}" 
IsVisible="{Binding IsOfferButtonVisible}"
/>

And then in your code behind
if(_credentialStatus == "Offered")
{
    IsOfferButtonVisible  = true;
}
else
{
    // Hide the Button
    IsOfferButtonVisible = false;
}

Method 2

Add a bool property to your ViewModel such as:

private bool _credentialVisible;
public bool CredentialVisible
{
    get 
    {
        return _credentialVisible;
    }
    set
    {
       if (_credentialVisible != value)
       {
           _credentialVisible = value;
           NotifyPropertyChanged();
       }
    }
}

Your view model should implement the interface INotifyPropertyChanged:
public event PropertyChangedEventHandler PropertyChanged;

protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Then in your View bind to the IsVisible property:
<Button x:Name="Button_Round"
IsVisible={Binding CredentialVisible}
WidthRequest="40"
HeightRequest="40"
CornerRadius="20"
BorderWidth="2"
TextColor="White"
BorderColor="Teal"
BackgroundColor="Teal"
Text="Accept Offer"
Command="{Binding ProcessOffer}" />

You didn’t specify when you need to check whether the button should be visible but I guess you need it when the page is loaded, in this case you need a behavior to trigger a command when the page is appearing, instead of writing it yourself you can use the following NuGet: https://www.nuget.org/packages/Behaviors.Forms/

Once installed, add the namespace to your ContentPage:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:behaviors="clr-namespace:Behaviors;assembly=Behaviors"

And then you can use it as follows:
<ContentPage.Behaviors>
    <behaviors:EventHandlerBehavior EventName="Appearing">
        <behaviors:InvokeCommandAction Command="{Binding AppearingCommand}" />
    </behaviors:EventHandlerBehavior>
</ContentPage.Behaviors>

That will call the method AppearingCommand when the page appears and you can set up the visibility of the button there:
public ICommand AppearingCommand => new Command(() =>
{
    if(_credentialStatus == "Offered")
    {
        CredentialsVisible = true;
    }
});


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x