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 MVVM databinding usercontrol


Sujet :

C#

  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2009
    Messages
    34
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2009
    Messages : 34
    Par défaut WPF MVVM databinding usercontrol
    Bonjour,
    j'aimerais savoir comment récupérer les données saisies dans mon usercontrol qui se trouve dans un window?
    j'explique: j'ai un UserControl, UserControl1.xaml, son ViewModel , UserControlVM.cs, dans lequel j'ai ceci (en fait j'ai une combobox et des checkbox, mais la je schématise) :
    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
     usercontrol1VM.cs
     
     private bool b_isCheckedTest;
            public bool IsCheckedTest
            {
                get
                {
                    return b_isCheckedTest;
                }
                set
                {
                    if (b_isCheckedTest != value)
                    {
                        b_isCheckedTest = value;
                        RaisePropertyChanged(() => IsCheckedTest);
                    }
                }
            }
     
    		usercontrol1.xaml
     
    		 <CheckBox Grid.Row="1"
                      Grid.Column="1"
                      HorizontalAlignment="Right"
                      VerticalAlignment="Center"
                      Content="Confirmation visuelle : "
                      FlowDirection="RightToLeft"
                      IsChecked="{Binding XPath=IsCheckedTest,
                                          Mode=TwoWay,
                                          UpdateSourceTrigger=PropertyChanged}" />
     
     
    		MainWindow.xaml
     
    		<local: usercontrol1 />
     
    		MainWindowVM.cs
    		jeveux recuperer la valeur de mon usercontrol1
    Merci d'avance de vos réponses

  2. #2
    Expert éminent Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 198
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 198
    Par défaut
    normalement il faudrait des propriétés cablées sur les propriétés des sous controles, et tant qu'à faire des propriétés qui puissent gérer du binding

    mais bon en wpf en général avec un datatemplate on a le même résultat qu'avec un usercontrol mais en plus simple
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  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

    Rappel-Entonnoir :
    On ne peut binder que des DP et non de simples CLR properties....Les CLR properties des class Data sont toujours bindes à des DP de Control ...
    exemple de UserControl (qui peut etre un Custom Control):
    code behind .cs :

    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
     
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.ComponentModel;
     
    namespace WpfExpandableDGV
    {
        /// <summary>
        /// Logique d'interaction pour UserControl1.xaml
        /// </summary>
        public partial class UserControl1 : UserControl
     
        {
            private int minValue = -5;
            private int maxValue = +5;
            public UserControl1()
            {
                InitializeComponent();
            }
     
     
            public bool IsChecked
            {
                get { return (bool)GetValue(IsCheckedProperty); }
                set { SetValue(IsCheckedProperty, value); }
            }
     
            // Using a DependencyProperty as the backing store for IsChecked.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty IsCheckedProperty =
                DependencyProperty.Register("IsChecked", typeof(bool), typeof(UserControl1 ), 
                new UIPropertyMetadata(true ));
     
     
     
            public int Value
            {
                get { return (int)GetValue(ValueProperty); }
                set { SetValue(ValueProperty, value); }
            }
     
            // Using a DependencyProperty as the backing store for Value.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty ValueProperty =
                DependencyProperty.Register("Value", typeof(int), typeof(UserControl1 ),
                new UIPropertyMetadata(0));
     
            private void chk1_Checked(object sender, RoutedEventArgs e)
            {
                Value++;
                if (Value > maxValue) Value = minValue;
            }
     
     
     
     
     
        }
    }
    code xaml :
    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
     
     
    <UserControl x:Class="WpfExpandableDGV.UserControl1"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 mc:Ignorable="d" 
                 d:DesignHeight="300" d:DesignWidth="300">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="auto" ></RowDefinition>
                <RowDefinition Height="auto" ></RowDefinition>
            </Grid.RowDefinitions>
            <DockPanel
                 Grid.Row="0">
                <TextBlock  
                    x:Name="tb" 
                    Background="Red"  Foreground="White" 
                    FontSize="14"
                    Text="{Binding Path=Value,
                    RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" >
                </TextBlock >
                <CheckBox  
                    x:Name="chk1" 
                    Background="Blue"   Foreground="White" 
                    FontSize="14"
                    Checked="chk1_Checked"
                   IsChecked="{Binding Path=IsChecked,
                    RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" >
                </CheckBox >
            </DockPanel>
     
            <CheckBox 
                Grid.Row="1"
                x:Name="chk2"
                Content="Confirmation visuelle : "
                IsChecked="{Binding Path=IsChecked,
                RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl }}}" >
     
            </CheckBox> 
     
        </Grid>
    </UserControl>
    Comme dit par Pol63 ,il vaut mieux un DataTemplate !!!
    bon code ...

  4. #4
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2009
    Messages
    34
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2009
    Messages : 34
    Par défaut
    Bonjour,
    merci de vos retours .
    J'ai une combobox :
    code xaml :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <ComboBox x:Name="cbx1"
                      Grid.Row="0"
                      Grid.Column="1"
                      Width="200"
                      Height="20"
                      HorizontalAlignment="Center"
                      VerticalAlignment="Center"
                      IsSynchronizedWithCurrentItem="True"
                      ItemsSource="{Binding Path=SelectedTypes,
                                             RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
                      SelectedItem="{Binding Path=SelectedType,
                                             RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
    code .cs :

    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
    public ObservableCollection<string> SelectedTypes
            {
                get { return (ObservableCollection<string>)GetValue(SelectedTypesProperty); }
                set
                {
                    SetValue(SelectedTypesProperty, value);
                }
            }
     
            public static readonly DependencyProperty SelectedTypesProperty =
               DependencyProperty.Register("SelectedTypes", typeof(ObservableCollection<string>), typeof(UserFieldDetailsV),
                   new PropertyMetadata(
                       new ObservableCollection<string>(),
                       (o, e) =>
                       {
                           if (e.NewValue == null)
                               return;
                       }
                   )
               );

    dans mon Mainwindow.xaml :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    <usfields:UserControlDetailsView />
    Par contre, dans mon viewmodel du mainwindow, je n'arrive pas à récupérer les données saisies dans la combobox et les valeurs des checkbox

    Je voulais créer un bouton dans le mainwindow qui récupère les valeurs saisies, comment faire ?
    Merci en tout cas de votre aides !!!!

  5. #5
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2009
    Messages
    34
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2009
    Messages : 34
    Par défaut
    De retour.
    Pour les checkbox j'ai résolu le problème, mais pour la combobox j' n'arrive toujours pas à atteindre la valeur saisie .

    dans mon mainwindow.cs
    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
    private ObservableCollection<string> e_SelectedTypesVM;
            public ObservableCollection<string> SelectedTypesVM
            {
                get
                {
                    return e_SelectedTypesVM;
                }
                set
                {
                    e_SelectedTypesVM = value;
     
                    RaisePropertyChanged(() => SelectedTypesVM);
                }
     
     public void LoadEnum()
            {
                SelectedTypesVM = new ObservableCollection<string>(Enum.GetNames(typeof(TypesVM)));
            }
            }
    ma combobox se charge bien mais le raisepropertychanged lorsque je choisi un élément ne marche pas.

  6. #6
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2009
    Messages
    34
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2009
    Messages : 34
    Par défaut
    ça y est j'ai trouvé .
    un peu de patience, beaucoup de travail et ça paye.
    En tout cas merci de votre aide , cela m'a guidée sur le bon chemin.

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

Discussions similaires

  1. [WPF][C#] Problème de TreeView avec MVvM sans UserControl
    Par Manwë06 dans le forum Windows Presentation Foundation
    Réponses: 9
    Dernier message: 05/10/2010, 13h23
  2. WPF et databinding : Best practice ?
    Par Emilie L. dans le forum Windows Presentation Foundation
    Réponses: 6
    Dernier message: 26/05/2010, 15h50
  3. [VS2008] Gros handicap du concepteur WPF avec les UserControl
    Par Obligen dans le forum Windows Presentation Foundation
    Réponses: 12
    Dernier message: 04/05/2009, 16h23
  4. WPF - Probleme Databinding (source de données Base Access)
    Par DonJR dans le forum Windows Presentation Foundation
    Réponses: 3
    Dernier message: 15/06/2008, 15h25

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