You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin.Forms中根据凭证状态控制按钮的显示与隐藏

Solution to Control Button Visibility Based on Credential Status

Got it, let's get your button visibility working correctly with your view model's credential status. Here's how to do it properly following MVVM best practices:

Step 1: Update Your CredentialViewModel to Support Property Change Notifications

First, we need to make sure your _credentialStatus is exposed as a bindable property, and add a computed property that determines the button's visibility. If your view model doesn't already implement INotifyPropertyChanged, you'll need to add that too—it's essential for MVVM updates to work.

Here's the updated view model code:

using System.ComponentModel;
using System.Runtime.CompilerServices;
using Xamarin.Forms;

public class CredentialViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    // Helper method to trigger property change notifications
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // Convert your private _credentialStatus to a public bindable property
    private string _credentialStatus;
    public string CredentialStatus
    {
        get => _credentialStatus;
        set
        {
            if (_credentialStatus != value)
            {
                _credentialStatus = value;
                OnPropertyChanged();
                // Notify that the visibility property has changed too, since it depends on this
                OnPropertyChanged(nameof(IsOfferButtonVisible));
            }
        }
    }

    // Computed property to control button visibility
    public Visibility IsOfferButtonVisible => CredentialStatus == "Offered" ? Visibility.Visible : Visibility.Collapsed;

    // Your existing ProcessOffer command stays the same
    #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
}

Step 2: Bind the Button's Visibility in XAML

Now update your CredentialPage.xml to bind the button's Visibility property to the new IsOfferButtonVisible property in your view model:

<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}"
        Visibility="{Binding IsOfferButtonVisible}" />

Key Notes:

  • Visibility.Collapsed vs Visibility.Hidden: I used Collapsed here because it removes the button from the layout entirely (no empty space left). If you want the button to take up space even when hidden, use Visibility.Hidden instead.
  • Property Change Notifications: When you update CredentialStatus, the OnPropertyChanged calls ensure the UI knows to refresh the button's visibility automatically.
  • MVVM Compliance: This approach keeps your UI and business logic separated, which is the core of MVVM design. You won't need to reference the button directly from your view model, which is a best practice.

内容的提问来源于stack exchange,提问作者user14139029

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 00:32:33