IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

[WPF] Binding entre 2 fenêtres


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé
    Inscrit en
    Octobre 2004
    Messages
    359
    Détails du profil
    Informations forums :
    Inscription : Octobre 2004
    Messages : 359
    Par défaut [WPF] Binding entre 2 fenêtres
    Bonjour,

    Je cherche à faire quelque chose, mais je ne sais pas si c’est possible ?

    Dans un projet avec 2 fenêtres, j’aimerai avoir sur la fenêtre 1 un bouton, et sur la fenêtre 2 un textbox.
    L’idée serait d’appuyer sur le bouton de la fenêtre 1 et alors le texte du textbox de la fenetre 2 affiche simplement "Hello world".

    Habituellement un binding en WPF avec des DependancyProperty sur la même fenêtre ne me pose pas de problème, mais je ne vois pas comment faire le binding du textbox avec le bouton de la fenetre 1 ?

    Si vous pouviez m’aider ça serait vraiment génial,
    Merci

  2. #2
    Membre éprouvé Avatar de WDKyle
    Homme Profil pro
    Analyste-Programmeur
    Inscrit en
    Septembre 2008
    Messages
    1 204
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Analyste-Programmeur

    Informations forums :
    Inscription : Septembre 2008
    Messages : 1 204
    Par défaut
    Bonsoir,

    Avec un viewmodel unique pour les 2 fenêtres ça doit etre faisable.

  3. #3
    Membre extrêmement actif
    Inscrit en
    Avril 2008
    Messages
    2 573
    Détails du profil
    Informations personnelles :
    Âge : 65

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 573
    Par défaut
    bonjour
    comme dit par WDKyle c'est possible .
    les ingrédients d'un class ViewModel sont :
    1/ implémenter INotifyPropertyChanged
    2/ une propriété derivée de ICommande
    3/ un class RelayCommand(ci-après ) qui implémente IComand

    exemple code .cs :

    1/ class RelayCommand (les commandes Wpf derivent de cette implementation)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    using System;
    using System.Windows.Input;
     
    namespace WpfApplication1
    {
        //The above code uses a RelayCommand which accepts two parameters: the method to execute, and a true/false value of if the command can execute or not. The RelayCommand class is a separate .cs file with the code shown below. I got it from Josh Smith :)
     
        public class RelayCommand : ICommand
        {
            #region Fields
     
            readonly Action<object> _execute;
            readonly Predicate<object> _canExecute;        
     
            #endregion // Fields
     
            #region Constructors
     
            /// <summary>
            /// Creates a new command that can always execute.
            /// </summary>
            /// <param name="execute">The execution logic.</param>
            public RelayCommand(Action<object> execute)
                : this(execute, null)
            {
            }
     
            /// <summary>
            /// Creates a new command.
            /// </summary>
            /// <param name="execute">The execution logic.</param>
            /// <param name="canExecute">The execution status logic.</param>
            public RelayCommand(Action<object> execute, Predicate<object> canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
     
                _execute = execute;
                _canExecute = canExecute;           
            }
     
            #endregion // Constructors
     
            #region ICommand Members
            public bool CanExecute(object parameters)
            {
                return _canExecute == null ? true : _canExecute(parameters);
            }
     
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
     
            public void Execute(object parameters)
            {
                _execute(parameters);
            }
     
            #endregion // ICommand Members
        }
    }
    2/ class ViewModel YourData
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    namespace WpfApplication1
    {
        // ce class évite par héritage  d'implementer INotifyPropertyChanged dans chaque class 
        // de  data éventuel(code  repetitif ou boiler-plate code)
        public class    ViewModelBase:INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
            public void Raise(string propName)
            {
                PropertyChangedEventHandler h = PropertyChanged;
                if (h != null)
                    h(this, new PropertyChangedEventArgs(propName));
            }
        }
     
     
    public class YourData : ViewModelBase
        {
            public YourData()
            {
     
            }
            // propriete texte à afficher
            private string mytext= "bonjour le monde";
            public string MyText
            {
                get { return mytext; }
                set { mytext = value; Raise("MyText"); }
            }
            // propriete satus permet de "flipper" ou basculer la prop texte à afficher
            private string status;
            public string Status
            {
                get { return status ; }
                set { status = value; Raise("Status"); }
            }
            // partie commande
            // propriete showTextCommand est la commande à executer
            private ICommand showTextCommand;
     
            public ICommand ShowTextCommand
            {
                get
                {
                    if (showTextCommand == null)
                    {
                        showTextCommand = new RelayCommand(
                            param => this.ShowText(),
                            param => this.CanShowText()
                        );
                    }
                    return showTextCommand;
                }
            }
            // methodes de la la logique de la commande.Ce que fait la commande.
            private bool CanShowText()
            {
                // Verify command can be executed here
                return  true; 
     
            }
     
            private void ShowText()
            {
                // Save command execution logic
                if (string.IsNullOrEmpty( this.Status))
                {
                   this.Status  = this.MyText;
                }
                else
                {
                    this.Status = string.Empty;
                }
            }
        }
    }
    code xaml du main form user :
    Code XAML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication1"
            Title="MainWindow" Height="350" Width="525"
            Loaded="Window_Loaded">
        <Window.DataContext >
            <local:YourData/>
        </Window.DataContext>
            <StackPanel Margin="5">
            <Button  Name="btn"  
                     Content="Display Status"
                     HorizontalAlignment="Center" VerticalAlignment="Top"
                     Command="{Binding ShowTextCommand}"
                     >
            </Button>
            <TextBox  
                x:Name="Status" 
                Height="23" HorizontalAlignment="Left"  VerticalAlignment="Top"
                Margin="50,80,0,0"  Width="120" 
                Text="{Binding Path=Status}"/>
        </StackPanel>
    </Window>
    code behind.cs de ce main form :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public partial class MainWindow : Window
        {
            private Window1 win1 = null;
            public MainWindow()
            {
                InitializeComponent();
            }
     
     
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                win1 = new Window1();
                win1.DataContext = this.DataContext;
                win1.Show();
     
            }
        }
    code xaml du form1 (window1) non modal:
    Code XAML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <Window x:Class="WpfApplication1.Window1"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Window1" Height="300" Width="300">
        <StackPanel >
            <TextBox  
                x:Name="Status" 
                Height="23" HorizontalAlignment="Left"  VerticalAlignment="Top"
                Margin="50,80,0,0"  Width="120" 
                Text="{Binding Path=Status}"/>
        </StackPanel> 
    </Window>
    bon code...

  4. #4
    Membre éclairé
    Inscrit en
    Octobre 2004
    Messages
    359
    Détails du profil
    Informations forums :
    Inscription : Octobre 2004
    Messages : 359
    Par défaut
    Citation Envoyé par MABROUKI Voir le message
    42
    Bonjour,

    J’ai essayé votre exemple, c’est parfait, exactement ce que je voulais faire, je suis vraiment ravi, merci beaucoup ! Je tag le sujet comme RÉSOLU.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Echange de valeurs entre deux fenêtres en C#-WPF
    Par Invité dans le forum Windows Presentation Foundation
    Réponses: 2
    Dernier message: 07/01/2014, 02h13
  2. Binding entre 2 contrôles WPF
    Par mascoco dans le forum Windows Presentation Foundation
    Réponses: 5
    Dernier message: 28/06/2010, 17h51
  3. binding entre un objet wpf et un objet COM
    Par TERRIBLE dans le forum Windows Presentation Foundation
    Réponses: 4
    Dernier message: 07/05/2010, 15h58
  4. Comment naviguer entre les fenêtres en WPF ?
    Par M.Mounir dans le forum Windows Presentation Foundation
    Réponses: 3
    Dernier message: 27/02/2009, 08h44
  5. [WPF] Problème de binding entre une SortedList et une ListBox
    Par Invité dans le forum Général Dotnet
    Réponses: 4
    Dernier message: 10/12/2007, 13h20

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo