【问题标题】:How to clear text box on click in MVVM如何在 MVVM 中单击时清除文本框
【发布时间】:2015-04-08 05:20:01
【问题描述】:

我有一个文本框和一个按钮,我想在单击按钮时清除文本框的内容。我正在使用 MVVM 棱镜。

我的 XAML

  <TextBox  Grid.Row="0" Text="{Binding 
       Path=TextProperty,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Name="txtUserEntry2"/>

   <Button Content="Select" 
       Command="{Binding Path=MyCommand}" />

在我的视图模型

    public string TextProperty
    {

        get
        {
            return selectedText;
        }
        set
        {

            selectedText = value;

            SetProperty(ref selectedText, value);
        }
    }

    //////.........

    private void MyCommandExecuted(object obj)
    {
        TextProperty= string.Empty;
        MessageBox.Show("Command Executed");
    }

但它不会清除文本框。我错过了什么?

【问题讨论】:

标签: c# wpf mvvm prism


【解决方案1】:

这是因为在您的设置器中,您设置了两次该字段,一次没有触发 PropertyChanged ,另一次触发 PropertyChanged ,在第二组中 SetProperty 将提高 PropertyChanged 仅当有一个新值时,但您已经设置字段设置为某个值,因此通过 SetProperty 设置的设置永远不会引发 PropertyChanged,因为您将其设置为相同的值。

所以在你的设置器中你应该删除:

selectedText = value;

【讨论】:

    【解决方案2】:

    您没有使用正确的属性名称“TextProperty”触发 PropertyChanged 事件 - 还是我遗漏了什么?我从来没有用过棱镜。 试试:

    public string TextProperty
    {
    
        get
        {
            return selectedText;
        }
        set
        {
            SetProperty(ref selectedText, value, "TextProperty");
        }
    }
    

    或者更好:

    private void MyCommandExecuted(object obj)
    {
        SetProperty(TextProperty, string.Empty);
        MessageBox.Show("Command Executed");
    }
    

    并从属性设置器中删除 SetProperty 调用。

    【讨论】:

    • 这不是 MVVM 约定。
    猜你喜欢
    • 1970-01-01
    • 2018-08-23
    • 2011-10-21
    • 2014-12-17
    • 1970-01-01
    • 2013-04-20
    • 2012-06-26
    • 1970-01-01
    • 2013-03-28
    相关资源
    最近更新 更多