我创建了一个模板,必须将变量的值分配给标签,我使用了绑定,但它不起作用。这是cs:中的代码
AppViewModel vm = new AppViewModel();
BindingContext = vm;
InitializeComponent();
这是视图模型中的代码:
public class AppViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _utente;
public AppViewModel()
{
Utente = App.UTENTE;
}
public string Utente
{
get
{
return _utente;
}
set
{
_utente = value;
//OnPropertyChanged("Utente");
//PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(Utente));
OnPropertyChanged("utente");
//PropertyChanged(this, new PropertyChangedEventArgs("utente"));
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
这是代码xaml:
<Label x:Name="utente" Padding="10, 0, 0, 0" Grid.Row="0" Grid.Column="0" Text="{Binding Utente}" FontSize="Large" TextColor="White" LineBreakMode="TailTruncation" VerticalOptions="Center" />
您没有正确使用MVVM,请参阅我的代码片段以供您参考。
1.在xaml和代码背后:
<StackLayout>
<Label Text="{Binding Utente}"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
xaml背后:
public partial class AppViewPage : ContentPage
{
AppViewModel vm = new AppViewModel();
public AppViewPage()
{
InitializeComponent();
BindingContext = vm;
vm.Utente = "utente";
}
}
2.AppViewModel:
public class AppViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _utente;
public string Utente
{
get { return _utente; }
set {
_utente = value;
PropertyChanged?.Invoke(this,
new PropertyChangedEventArgs(nameof(Utente)));
}
}
public AppViewModel()
{
}
}