如何在 Xamarin.Forms 中使用 XAML 中的 C# 变量的值?



我是Xamarin.forms和C#的新手,我正在使用名为userac.xaml的Xaml创建用户帐户页面,其中将有一个标签说"Hello,[用户名]",userac.xaml中有一个字符串变量.cs其中包含用户名,该用户名将在userac.xaml页面中显示为"Hello, [用户名]",但我不知道该怎么做。请帮忙。

我附上了代码:-

<StackLayout>
<Label Text=""
VerticalOptions="CenterAndExpand" 
HorizontalOptions="CenterAndExpand" />
</StackLayout>

userac.xaml.cs:-

public partial class userac : ContentPage
{
public Contracts()
{
InitializeComponent();
}
}

应使用数据绑定。
另外,正如您所说,您是C#语言的新手,因此,如果您不熟悉C#属性声明,则可以在示例中看到(代码中的get()set()方法(,请阅读此内容。

请根据您的代码查看示例中的注释:

.XAML:

<StackLayout>
<Label Text="{Binding TheUserName}"
VerticalOptions="CenterAndExpand" 
HorizontalOptions="CenterAndExpand" />
</StackLayout>

。.CS:

public partial class userac : ContentPage
{
private string _TheUserName = "Some User Name";
public string TheUserName
{
get
{
return "Hello " + _TheUserName;
}
set
{
_TheUserName = value;
// read here about OnPropertyChanged built-in method https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.bindableobject.onpropertychanged?view=xamarin-forms
OnPropertyChanged("TheUserName");
}
}
public userac()
{
// Note: binding context can also to another view model class of this view, but here we will use the class of this specific view
// So, you can also do something like that:
// BindingContext = new useracViewModel() 
BindingContext = this;
// you can also change the default value of _TheUserName by getting it from database, xml file etc...
TheUserName = GetCurrentUserName();
InitializeComponent();
}
private string GetCurrentUserName()
{
// ...
// do things to retrieve the user name...
// ...
return "John Doe";
}
}

最新更新