【问题标题】:Clear entry text from ViewModel using RelayCommand使用 RelayCommand 从 ViewModel 中清除条目文本
【发布时间】:2022-01-01 22:38:07
【问题描述】:

我想从绑定在那里的 ViewModel 中清除条目文本。在下面的代码中,我尝试使用 RelayCommand,但它不起作用。

我想要完成的事情:单击名为AddQuestionToQuiz 的按钮时,通过在按钮上使用命令来执行一个函数。我的 ViewModel 中的函数OnCreateQuizClick() 被触发,这个函数需要清除我的输入文本,我暂时没有。

我也尝试使用常规命令而不是使用 RelayCommand,但在这里它也不想工作。

编辑:底层代码工作正常 - 已更新 代码用于在单击 ViewModel 中的按钮时清除条目文本,实现 INotifyPropertyChanged 接口

.xaml - 代码

<Button x:Name="AddQuestionToQuiz" WidthRequest="200" Command="{Binding CreateQuizCommand}" Style="{StaticResource ButtonStyle}" Text="Add question to quiz"></Button>

ViewModel - 代码

internal class CreateQuizPageViewModel : INotifyPropertyChanged
{
    // Quiz Name Input
    public String QuizNameInput { get; set; }

    private String quizQuestionInput = "";
    public String QuizQuestionInput 
    {
        get { return quizQuestionInput; }   
        set { quizQuestionInput = value; OnPropertyChanged(); }
    } 

    public RelayCommand CreateQuizCommand { get; set; }

    public CreateQuizPageViewModel()
    {
        CreateQuizCommand = new RelayCommand(OnCreateQuizClick);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public void OnCreateQuizClick()
    {
        QuizQuestionInput = "";
    }
}

【问题讨论】:

  • 您的 VM 未实现 INotifityPropertyChaged,因此 UI 不会收到有关 VM 更改的通知
  • 我通过一个工作示例编辑了上面的代码(ViewModel 已更新),谢谢@Jason。也可以通过使用普通命令而不是中继命令来工作
  • 不要将工作代码添加到问题中,而是将其添加为下面的“您的答案”。这使任何看到此问题的人都更容易意识到它已被回答。谢谢。

标签: xamarin.forms binding command relaycommand


【解决方案1】:

编辑:视图模型已更新

.xaml - 代码

<Button x:Name="AddQuestionToQuiz" WidthRequest="200" Command="{Binding CreateQuizCommand}" Style="{StaticResource ButtonStyle}" Text="Add question to quiz"></Button>

ViewModel - 代码

internal class CreateQuizPageViewModel : INotifyPropertyChanged
{
    // Quiz Name Input
    public String QuizNameInput { get; set; }

    private String quizQuestionInput = "";
    public String QuizQuestionInput 
    {
        get { return quizQuestionInput; }   
        set { quizQuestionInput = value; OnPropertyChanged(); }
    } 

    public RelayCommand CreateQuizCommand { get; set; }

    public CreateQuizPageViewModel()
    {
        CreateQuizCommand = new RelayCommand(OnCreateQuizClick);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public void OnCreateQuizClick()
    {
        QuizQuestionInput = "";
    }
}

【讨论】:

    猜你喜欢
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 2016-11-09
    • 2011-11-04
    • 2022-01-18
    • 2012-02-01
    相关资源
    最近更新 更多