簡體   English   中英

在WPF中清除多個文本框值

[英]Clear multiple textbox value in wpf

我想在按下按鈕時清除所有文本框值。我在winform中使用了此代碼,這很好用,但是當我嘗試在wpf中使用相同的代碼時,在this.Controls位置出現了錯誤。這是代碼。請給我一個解決方案。

foreach (Control c in this.Controls)                 
    if (c is TextBox) 
       (c as TextBox).Clear(); 

我建議研究WPF的MVVM模式來解決您的問題。

通過將視圖(XAML)中的文本框和按鈕綁定到視圖模型(類),可以直接在button命令中清除文本框值。 有很多不錯的MVVM框架,例如: CinchMVVM light可以幫助您入門。

這是使用Cinch的示例,但重要的是:
1.第0行中的TextBox使用TwoWay綁定到Text1
2.第1行中的TextBox使用TwoWay綁定到Text2
3.第2行中的按鈕使用Command綁定到Clearcommand,從而將Text1和Text2設置為string.Empty

這是視圖:

<Window x:Class="TextboxClear.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:meffed="clr-namespace:MEFedMVVM.ViewModelLocator;assembly=MEFedMVVM.WPF" 
    meffed:ViewModelLocator.ViewModel="MainWindowViewModel"            
    Title="MainWindow" Height="350" Width="525">
  <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <TextBox Grid.Row="0" Text="{Binding Path=Text1, Mode=TwoWay}"/>
    <TextBox Grid.Row="1" Text="{Binding Path=Text2, Mode=TwoWay}"/>
    <Button Grid.Row="2" Content="Clear" Command="{Binding Path=ClearCommand}"/>
  </Grid>
</Window>

這是視圖模型:

using System;
using System.ComponentModel.Composition;
using Cinch;
using MEFedMVVM.ViewModelLocator;

namespace TextboxClear.ViewModels
{
  [ExportViewModel("MainWindowViewModel")]
  [PartCreationPolicy(CreationPolicy.Shared)]
  public class MainWindowViewModel : ViewModelBase
  {
    [ImportingConstructor]
    public MainWindowViewModel()
    {
      ClearCommand = new SimpleCommand<Object, Object>(CanExecuteClearCommand, ExecuteClearCommand);
    } 

    private string _text1 = string.Empty;
    public string Text1
    {
      get
      {
        return _text1;
      }
      set
      {
        _text1 = value;
        NotifyPropertyChanged("Text1");
      }
    }  

    private string _text2 = string.Empty;
    public string Text2
    {
      get
      {
        return _text2;
      }
      set
      {
        _text2 = value;
        NotifyPropertyChanged("Text2");
      }
    }

    public SimpleCommand<Object, Object> ClearCommand { get; private set; }
    private void ExecuteClearCommand(Object args)
    {
      Text1 = string.Empty;
      Text2 = string.Empty;
    }

    private bool CanExecuteClearCommand(Object args)
    {
      return true;
    }
  }
}

使用VisualTreeHelper.GetChild()。 例如,如果您的文本框位於稱為StackPanelNew的StackPanel中,請使用

  for (int i = 0;i < VisualTreeHelper.GetChildrenCount(this.StackPanelNew);i++) {
    TextBox txt = VisualTreeHelper.GetChild(this.StackPanelNew, i) as TextBox;
    if (txt != null)
    {
      //do stuff
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM