我最近开始学习 Xamarin,我偶然发现了以下问题。我的 XAML 文件中有一个标签绑定(bind)到 ViewModel 属性。我正在使用 ICommand 接口(interface)将点击手势绑定(bind)到我的 ViewModel 中的一个方法,该方法应该更新标签的文本。但是,它没有更新“请触摸我一次!”。我只是想知道我在这里做错了什么?
主页 xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App1"
x:Class="App1.MainPage">
<Label Text="{Binding MessageContent, Mode=TwoWay}"
VerticalOptions="Center"
HorizontalOptions="Center">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding OnLabelTouchedCmd}" />
</Label.GestureRecognizers>
</Label>
</ContentPage>
代码隐藏:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = new MainPageViewModel();
}
}
View 模型:
class MainPageViewModel : INotifyPropertyChanged
{
private string _messageContent;
public MainPageViewModel()
{
MessageContent = "Please touch me once!";
OnLabelTouchedCmd = new Command(() => { MessageContent = "Hey, stop toutching me!"; });
}
public ICommand OnLabelTouchedCmd { get; private set; }
public string MessageContent
{
get => _messageContent;
set
{
_messageContent = value;
OnPropertyChanged(value);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
最佳答案
您正在调用 OnPropertyChanged有一个错误的论点,如下所示:
protected virtual Void OnPropertyChanged ([System.Runtime.CompilerServices.CallerMemberName] String propertyName)
它需要属性的名称而不是您现在传递的值。试试这个:
public string MessageContent
{
get => _messageContent;
set
{
_messageContent = value;
OnPropertyChanged("MessageContent");
}
}
关于c# - 我的绑定(bind)标签没有改变 [INotifyPropertyChanged],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46014265/