Je recommande à la recherche dans le modèle MVVM pour WPF pour résoudre votre question. En associant une zone de texte et un bouton dans votre vue (XAML) à un modèle de vue (classe), vous pouvez effacer les valeurs de la zone de texte directement dans la commande de bouton. Il y a beaucoup de bons frameworks MVVM comme: Cinch et MVVM light pour vous aider à démarrer.
Voici un exemple qui utilise Cinch, mais ce qui est important est:
1. TextBox dans la ligne 0 utilise TwoWay se liant à Texte1
2. TextBox dans la ligne 1 utilise la liaison TwoWay à Texte2
3. Bouton en ligne 2 utilise la liaison de commande pour Clearcommand qui définit Texte1 et Texte2 à String.Empty
Voici la vue:
<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>
Voici le modèle de vue:
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;
}
}
}
Pour que le code soit formaté en code, vous devez placer quatre espaces avant chaque ligne. Il y a aussi un bouton qui ressemble à ceci: '{}'. Je l'ai fait pour toi cette fois. –
Quelle erreur? Compilateur, exception d'exécution? Quel était le message? – ChrisF
Quel est le type de 'this'? Je ne pense pas que les éléments WPF exposent une propriété 'Controls', mais si' this' dérive de 'Panel', vous pouvez utiliser son [' Children'] (http://msdn.microsoft.com/fr-fr /library/system.windows.controls.panel.children.aspx) propriété à la place. –