Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Xamarin表单按钮文本绑定失败_C#_Xamarin_Data Binding_Xamarin.forms - Fatal编程技术网

C# Xamarin表单按钮文本绑定失败

C# 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

我正在尝试将字符串绑定到按钮文本

这是我的viewmodel

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的公共属性中更改的属性