Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.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# 如何在MVVM中单击时清除文本框_C#_Wpf_Mvvm_Prism - Fatal编程技术网

C# 如何在MVVM中单击时清除文本框

C# 如何在MVVM中单击时清除文本框,c#,wpf,mvvm,prism,C#,Wpf,Mvvm,Prism,我有一个文本框和一个按钮,我想在点击按钮时清除文本框的内容。我使用的是MVVM棱镜 我的XAML是 <TextBox Grid.Row="0" Text="{Binding Path=TextProperty,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Name="txtUserEntry2"/> <Button Content="Select" Command="{Bindi

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

我的XAML

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

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

但它并没有清除文本框。我遗漏了什么?

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

或者更好:

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

并从属性setter中删除SetProperty调用

这是因为在setter中,您设置了两次字段,一次未触发PropertyChanged,另一次触发PropertyChanged,在第二组
SetProperty
中,只有在有新值时才会引发
PropertyChanged
,但是您已经将字段设置为某个值,因此通过
SetProperty
设置的集合将永远不会引发PropertyChanged,因为您正在将其设置为相同的值

因此,在setter中,您应该删除:

selectedText = value;

看,这不是MVVM惯例。
private void MyCommandExecuted(object obj)
{
    SetProperty(TextProperty, string.Empty);
    MessageBox.Show("Command Executed");
}
selectedText = value;