C# Xamarin表单按钮文本绑定失败
我正在尝试将字符串绑定到按钮文本 这是我的viewmodelC# Xamarin表单按钮文本绑定失败,c#,xamarin,data-binding,xamarin.forms,C#,Xamarin,Data Binding,Xamarin.forms,我正在尝试将字符串绑定到按钮文本 这是我的viewmodel public class MainPageViewModel : BaseViewModel { private IUserDialogs _dialog; private const string START = "Start"; private const string STOP = "Stop"; public ICommand Start { get; } public string
public class MainPageViewModel : BaseViewModel
{
private IUserDialogs _dialog;
private const string START = "Start";
private const string STOP = "Stop";
public ICommand Start { get; }
public string startText { get; set; }
public MainPageViewModel(IUserDialogs dialogManager)
{
_dialog = dialogManager;
Start = new Command(()=>toggleStart());
startText = START;
}
private void toggleStart()
{
if(startText.Equals(START))
{
startText = STOP;
_dialog.Toast("Start Monitoring");
}
else if (startText.Equals(STOP))
{
startText = START;
}
}
}
这是我的xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ble.net.sampleapp.view.MainPage"
Title="Monitor">
<RelativeLayout>
<Button Text="{Binding startText}"
Command="{Binding Start}"/>
</RelativeLayout>
</ContentPage>
我想让按钮文本在按下时在开始和停止之间变化。但是,它最初显示Start,当我按下它时不会改变。我已经测试了命令绑定工作正常。为了使视图考虑到
startText
的更改,您必须通知该属性的更改。它解释了PropertyChanged
和一些实现
我不太确定您的BaseViewModel
是什么,但我认为它实现了INotifyPropertyChanged
。因此,在属性的setter中,必须调用PropertyChanged?.Invoke(这是新的propertychangedventargs(propertyName))代码>,即:
private string _startText;
public string StartText
{
get => this._startText;
set
{
this._startText;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(StartText)));
}
}
这样,当引发PropertyChanged
时,您的视图将被通知更新其值
显然,可以通过使用属性名调用事件的方法进行改进
您还可以使用自动提升ViewModels的公共属性中更改的属性
嗨