清除wpf中的多个文本框值

时间:2010-12-31 12:06:04

标签: wpf

当我按下按钮时,我想要清除所有文本框值。我使用此代码在winform中工作正常,但是当我尝试在wpf中使用相同的代码时,此错误发生在此。控件位置。这是代码。请给我一个解决方案。

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

2 个答案:

答案 0 :(得分:1)

我建议查看WPF的MVVM模式来解决您的问题。

通过将视图中的文本框和按钮(XAML)绑定到视图模型(类),可以直接在按钮命令中清除文本框值。有许多好的MVVM框架,例如:CinchMVVM light可以帮助您入门。

以下是使用Cinch的示例,但重要的是:
 1.第0行中的TextBox使用TwoWay绑定到Text1
 2.第1行中的TextBox使用TwoWay绑定到Text2
 3.第2行中的按钮使用命令绑定到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;
    }
  }
}

答案 1 :(得分:0)

使用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
    }
  }
相关问题