清除文本框

时间:2017-12-11 07:40:58

标签: c# wpf mvvm textbox

我正在制作输入页面而我正在尝试实施重置按钮。点击按钮后,UI应该再次为空。

我认为输入一个空字符串会解决这个问题。在代码中它似乎工作,价值确实变为""但是在UI中,键入的文本保持可见(因此它不会显示空的""字符串)。我也尝试使用here中建议的string.Empty,但这似乎也不起作用。

我在这里遗漏了什么吗?我对编程有点新意,所以如果我做了一些可怕的错误,不要笑得太厉害;)

我使用MVVM模式和Fody Weaver处理属性改变了部分代码。

UI / XAML

<TextBlock Text="Naam:"
           Grid.Column="0"
           Style="{StaticResource InputInputBlock}"
           />

<TextBox Foreground="White"
         Grid.Column="1"
         Text="{Binding Name, Mode=TwoWay}"
         Style="{StaticResource InputInputBox}"
         />

<Button Content="Reset"
            Height="50"
            Width="150"
            Grid.Column="0"
            Grid.Row="2"
            VerticalAlignment="Top"
            HorizontalAlignment="Center"
            Style="{StaticResource FlatButton}"
            Command="{Binding ResetCommand}"
            />

视图模型

private string _name;
public string Name
        {
            get => _name;
            set
            {
                _name = value;
            }
        }
public AddStakeholderViewModel()
        {
            ResetCommand = new RelayCommand(() => ResetForm());
        }

private void ResetForm()
        {
            Name = " ";
        }

1 个答案:

答案 0 :(得分:1)

您可以在班级中实施INotifyPropertyChanged界面。这对我有用:

public class Person : INotifyPropertyChanged
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                // Call OnPropertyChanged whenever the property is updated
                OnPropertyChanged("Name");
            }
        }

        // Declare the event
        public event PropertyChangedEventHandler PropertyChanged;

        // Create the OnPropertyChanged method to raise the event
        protected void OnPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }

XAML:

<TextBox Foreground="White"
     Grid.Column="1"
     Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
     Style="{StaticResource InputInputBox}"
     />

主窗口:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = newPerson;
    }
    Person newPerson = new Person();
    private void button_Click(object sender, RoutedEventArgs e)
    {
        newPerson.Name = "";
    }
}