简体   繁体   中英

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
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM