首页 > 解决方案 > 我无法使用 Xamarin Forms 中的命令更新屏幕

问题描述

我正在尝试制作一个 ImageButton,当我单击它时,可以看到其他按钮。默认情况下,其他 ImageButton 是不可见的。

我知道我必须刷新屏幕,但我不知道该怎么做。我尝试使用“INotifyPropertyChanged”,但它不起作用。

MainPage.xaml:

MainPage.xaml(我无法粘贴代码,我不知道为什么)

ViewModel.cs:

public class ViewModel
{

    public string ImageSource { get; set; }
    public string ButtonColor { get; set; }
    
    public string IsVisible2 { get; set; }

    public string Website { get; set; }
   // public Command<string> OpenAppCommand { get; set; }

    public Command OpenAppCommand { get; }
    public Command OpenFloating { get; }



    public ViewModel()
    {
        OpenAppCommand = new Command(launcWeb);
        OpenFloating = new Command(openFloatingButton);

        IsVisible2 = "false";          
        ImageSource = "share256white.png";
        ButtonColor = "red";
    }


    
    public void launcWeb()
    {
        Website = "https://facebook.com";
        Device.OpenUri(new Uri(Website));
    }

   //===============================
    
    Boolean firstStart = true;
    Boolean nextClick = true;

    public void openFloatingButton()
    {

        
        if (firstStart)
        {

            IsVisible2 = "true";
            firstStart = false;


        }
        else
        {


            if (nextClick)
            {

                IsVisible2 = "false";
                nextClick = false;

            }
            else
            {

                IsVisible2 = "true";
                nextClick = true;

            }



        }
    }
    }

标签: c#xamarinxamarin.forms

解决方案


首先,您的IsVisible2财产应该是bool

例如

public bool IsVisible2 { get; set; }

其次,没有证据表明您的INotifyPropertyChanged实施可能是它不起作用的原因。关于如何实现它的文档可以在这里找到

您需要在您的ViewModel类上实现该接口。

就像是:

public class ViewModel : INotifyPropertyChanged
{
    private bool isVisible2;

    public bool IsVisible2
    {
        get => isVisible2;
        set
        {
            isVisible2 = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;  

    // This method is called by the Set accessor of each property.  
    // The CallerMemberName attribute that is applied to the optional propertyName  
    // parameter causes the property name of the caller to be substituted as an argument.  
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")  
    {  
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    } 
}

推荐阅读