Xamarin表单-如何在代码中“绑定”字符串?

时间:2018-08-02 07:36:38

标签: c# xamarin

我尝试做这些

UserInformation.xaml

<StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="Center">
    <Label Text="Name" />
    <Label Text="{Binding  name}"/>
</StackLayout>

Userinformation.xaml.cs

    public async Task GetinfoAsync()
    {

        string name = "Jeremy";

        this.BindingContext = this;

    }

如何在xaml中显示变量名?

1 个答案:

答案 0 :(得分:2)

您必须使用Binding属性而不是局部变量:

class YourViewModel : INotifyPropertyChanged
{
    string name;

    public event PropertyChangedEventHandler PropertyChanged;


    public string Name
    {
        set
        {
            if (name != value)
            {
                name = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
                }
            }
        }
        get
        {
            return name;
        }
    }
}

然后使用具有name属性的viewmodel类:

public async Task GetinfoAsync()
{
    var vm = new MyViewModel();

    vm.Name = "Jeremy";

    this.BindingContext = vm;

}

xaml代码:

<StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="Center">
    <Label Text="Name" />
    <Label Text="{Binding Name}"/>
</StackLayout>