首页 > 解决方案 > 如何访问元素 xamarin 表单的属性?

问题描述

如何从 Android 和 IOS 项目访问 xamarin 表单中页面元素的属性?

例如:

Button1.IsVisible = false;

但自从Android项目。

标签: xamarin.forms

解决方案


您可以在文件隐藏代码中访问页面元素的属性,但这通常不是一个好的或干净的策略。

一个简单的示例是 Page.xaml:

<Button x:Name="Button1" Content="Sample String"/>

然后在你的 Page.xaml.cs

Button1.IsVisible = false; 

更好的方法是您可能想查看DataBinding机制: https ://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/

作为一个小示例,您将拥有一个实现 INotifyPropertyChanged 的​​ BindingContext/ViewModel。有了它,你可以这样:

private bool _isVisible;
public bool IsVisible 
{
    get => this._isVisible;
    set 
    {
        if(this._isVisible != value){
            this.IsVisible;
    }
}

然后在您的 Page.xaml 中:

<Button IsVisibile="{Binding IsVisible} Content="Sample String"/>

您可以在 Page.xaml.cs 中设置 BindingContext:

this.BindingContext = new ViewModel(); //If the properties are in a separate class (preferred)
this.BindingContext = this; //If the properties are in the page class  

推荐阅读