How to clear text box on click in MVVM

℡╲_俬逩灬. 提交于 2019-12-31 03:03:07

问题


I have a textbox and a button I want to clear the contents of textbox on button click. I am using MVVM prism.

My XAML is

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

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

and In my View Model

    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");
    }

But it does not clear the textbox. What am I missing ?


回答1:


Its because in your setter you are setting the field twice, one without firing PropertyChanged and the other with firing PropertyChanged , in the second set SetProperty will raise PropertyChanged only if there is a new value, but you already set the field to some value so the set through the SetProperty will never raise PropertyChanged because you are setting it to the same value.

So in your setter you should remove:

selectedText = value;



回答2:


You are not triggering the PropertyChanged-event with the correct property name "TextProperty" - or am I missing something? I've never used Prism. Try:

public string TextProperty
{

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

or better yet:

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

and remove the SetProperty call from the property setter.



来源:https://stackoverflow.com/questions/29506530/how-to-clear-text-box-on-click-in-mvvm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!