我尝试做这些
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中显示变量名?
答案 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>