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

Windows Presentation Foundation Discussion :

binding sur une variable définie dans un .cs [Débutant]


Sujet :

Windows Presentation Foundation

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éprouvé
    Avatar de Rakken
    Homme Profil pro
    Inscrit en
    Août 2006
    Messages
    1 257
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 1 257
    Par défaut binding sur une variable définie dans un .cs
    Bonjour

    J'ai une listbox et dedans, je veux dessiner un rectangle avec une hauteur définie dans mon mainWindow.xaml.cs, et je n'arrive pas à faire le bind.

    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
     <DataTemplate 
                x:Key="CardTemplate"
                DataType="{x:Type local:Card}">
                <Border Background="Transparent"
    					BorderBrush="DarkGray"
    					BorderThickness="0,0,0,0"
    					Padding="0">
                    <!-- Contenu d'une carte -->
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="10" Name="cardKeywordColumn" />
                            <ColumnDefinition Width="10" />
                            <ColumnDefinition Width="50*" />
                        </Grid.ColumnDefinitions>
                        <Rectangle Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Top" Name="rectLabel" Stroke="{x:Null}" Width="10" Height="{Binding Path=cardHeight, Source=MainWindow}" Fill="{Binding colorText}" />
                        <Rectangle Grid.Column="1" HorizontalAlignment="Left" Stroke="{x:Null}" Width="9" Fill="#00000000" />
                        <TextBlock Grid.Column="2" Name="tbListCardText" Text="{Binding text}" Background="{Binding colorText}" Visibility="{Binding nouvellePropriete}" />
                        <Rectangle Grid.Column="2" HorizontalAlignment="Right" Width="2" Margin="4" Name="rectangle2" Stroke="Black" Fill="Black" FlowDirection="RightToLeft" />
                    </Grid>
                </Border>
            </DataTemplate>

    En fait, c'est la valeur "Height" que je voudrai lier à la variable "cardHeight" que j'ai définie dans mainWindow.xaml.cs.
    J'ai tenté "Height="{Binding Path=cardHeight, Source=MainWindow}"", mais assurément, ça ne fonctionne pas.
    (Les autres valeurs viennent d'une classe "Card" qui défini le contenu d'une carte, mais la hauteur étant juste un paramètre d'affichage, l'introduire dans ma classe Card me semble être une pure absurdité).

    Merci d'avance !

  2. #2
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par Rakken Voir le message
    J'ai tenté "Height="{Binding Path=cardHeight, Source=MainWindow}"", mais assurément, ça ne fonctionne pas.
    Je pense que tu dois passer par la propriété RelativeSource et pas Source comme tu le fais.

    Essaie la ligne suivante :
    Code xml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    Height="{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"

  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 rakken

    Approche 1
    on utilise sur le winform ou usercontrol soit :
    - des Property CLR normales
    - des Dependency Property
    ca necessite de :
    - mettre DataContext du form ou usercontrol sur lui meme:l
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
     public MainWindow()
            {
                InitializeComponent();
                this.DataContext = this;
            }
    -Code xaml à utiliser dans le DataTemplate du ListBox :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    <--la prop CustomHeight est definie comme un dependency property sur le MainWindow -->
    <!--remonte le datatcontext vers un type window--> 
                        <Rectangle 
                            Height="{Binding DataContext.CustomHeight,
                            RelativeSource={RelativeSource 
                            AncestorType={x:Type  Window}},Mode=TwoWay}"/>
    Rakken feras observer que l'on ne peut plus le datacontext sur le viewmodel....ce qui obligerait d'utiliser itemsSource pour chaque control....

    Aussi je te recommende la solution "more simplistic" qui suit:
    Approche 2:
    -un simple class Utility declare en static resource Xaml.
    -grand avantage : les staticresources participent au DataContext global de facto........sans aucun effort de notre part.....

    code du class Card exemple deja vue par ailleurs:
    code .cs Card
    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
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel;
    using System.Collections.ObjectModel;
    using System.Windows.Media;
    namespace WpfBindingRectangle
    {
        public class Card:INotifyPropertyChanged
        {
            public Card()
            { }
            public Card(string t)
            {
                text = t;
     
            }
            private string m_text;
            public string text 
            {
                get { return m_text; }
                set
                {
                    m_text=value ; OnPropertyChanged("text");
                }
            }
     
     
     
            #region INotifyPropertyChanged Membres
     
            public event PropertyChangedEventHandler PropertyChanged;
            private void OnPropertyChanged(string propName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propName));
     
                }
     
            }
            #endregion
        }
        public class Cards:ObservableCollection<Card>
        {
            public Cards() 
            {
                for (int i = 0; i < 3; i++)
                {
     
                    this.Add(new Card("item"+i.ToString()));
     
                }
     
            }
     
        }
    }
    code xaml winform:
    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
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
     
    <Window x:Class="WpfBindingRectangle.Window3"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfBindingRectangle"
            Title="Window3" Height="300" Width="300"
            Name="MyWindow">
        <Window.Resources>
            <!--tu peux eb mode design utiliser le static resource myDataSource-->
            <!--pour voir l'efficacite du procede-->
            <!--<local:Cards x:Key="myDataSource"></local:Cards>-->
     
            <local:UtilityClass x:Key="util"></local:UtilityClass>
            <DataTemplate 
                x:Key="CardTemplate"
                DataType="{x:Type local:Card}">
                <Border 
                    Background="Transparent"
    				BorderBrush="DarkGray"
    				BorderThickness="1,1,1,1"
    				Padding="0">
                    <!--Contenu d'une carte-->
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" Name="cardKeywordColumn" />
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <!--ton rectangle espion binde à property MyHeight-->
                        <Rectangle 
                            Grid.Column="0" 
                            HorizontalAlignment="Left" 
                            VerticalAlignment="Top"
                            Name="rectLabel"
                            Width="50"
                            Fill="LightBlue"  
                            Stroke="Brown"  
                            Height="{Binding Source={StaticResource util},Path=MyHeight}">
                        </Rectangle>
                        <!--textblock espion binde à property MyText-->
                        <TextBlock 
                            Grid.Column="1"
                            Name="tbCustomText" 
                            Padding="10"
                            Background="NavajoWhite" 
                            Text="{Binding Source={StaticResource util},Path=MyText}">
                        </TextBlock>
                        <!--ton textblock binde à text-->
                        <TextBlock 
                            Grid.Column="2"
                            Padding="10"
                            Name="tbListCardText" 
                            Background="Yellow" 
                            Text="{Binding text}"  >
                        </TextBlock>
     
                    </Grid>
                </Border>
            </DataTemplate>
        </Window.Resources>
        <StackPanel Orientation="Vertical" >
            <StackPanel Orientation="Horizontal" >
                <!--textblock binde à property CustomText-->
                <Label 
                    Name="lblCustomText"
                    Foreground="Black"   
                    Content=" Enter a text :">
                </Label>
                <TextBox  
                    Name="txtCustomText"
                    Foreground="Red"  
                    Width="100"
                    Text="{Binding Source={StaticResource util}, Path=MyText}">
                </TextBox>
            </StackPanel>
            <!--textblock binde à property CustomHeight-->
            <StackPanel Orientation="Horizontal">
                <Label  
                    Name="lblCustomHeight"
                    Foreground="Black"   
                    Content=" Enter a height :">
                </Label >
                <TextBox  
                    Name="txtCustomHeight"
                    Foreground="Red"  
                    Text="{Binding Source={StaticResource util}, Path=MyHeight}">
                </TextBox>
            </StackPanel>
            <ListBox
                 Name="lb"
                 ItemTemplate="{StaticResource CardTemplate}"
                 ItemsSource="{Binding}">
            </ListBox>
        </StackPanel>
    </Window>
    code .cs du winform avec le class UtilityClass:
    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
    77
    78
    79
    80
    81
    82
    83
     
    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.Shapes;
    using System.ComponentModel;
     
    namespace WpfBindingRectangle
    {
        /// <summary>
        /// Logique d'interaction pour Window3.xaml
        /// </summary>
        public partial class Window3 : Window
        {
            private Cards MyList;
     
            public Window3()
            {
                InitializeComponent();
               //schema viewmodel habituel 
     
                MyList = new Cards();
                this.DataContext = MyList;
            }
     
     
        }
        public class UtilityClass : INotifyPropertyChanged
        {
            public  UtilityClass()
            {
                this.MyText = "hello,text";
                this.MyHeight = 60.0;
            }
            public UtilityClass(string t,double d)
            {
                this.MyText = t;
                this.MyHeight = d;
            }
            private string _MyText;
            public string MyText
            {
                get { return _MyText; }
                set
                {
                    _MyText = value; OnPropertyChanged("MyText");
                }
            }
            private double _MyHeight;
            public double MyHeight
            {
                get { return _MyHeight; }
                set
                {
                    _MyHeight = value; OnPropertyChanged("MyHeight");
                }
            }
     
     
     
            #region INotifyPropertyChanged Membres
     
            public event PropertyChangedEventHandler PropertyChanged;
            private void OnPropertyChanged(string propName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propName));
     
                }
     
            }
            #endregion
        }
    }
    A toi d'apprecier suivant le besoin ...............
    bon code..............

  4. #4
    Membre éprouvé
    Avatar de Rakken
    Homme Profil pro
    Inscrit en
    Août 2006
    Messages
    1 257
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 1 257
    Par défaut
    Rakken feras observer que l'on ne peut plus le datacontext sur le viewmodel....ce qui obligerait d'utiliser itemsSource pour chaque control....
    Qu'on ne peut plus quoi ?


    J'ai regardé la valeur de datacontext pendant l'exécution de mon programme, et de fait, cette valeur était systématiquement vide. Du coup, j'ai tenté la première solution et, oh joie, ça marche.
    J'ai juste adapté un petit peu. J'ai une classe dédiée au stockage de mes données, et du coup, c'est cette nouvelle classe que j'ai mis dans mon "datacontext". Ca me semblait plus propre.

    En tout cas, merci beaucoup !
    (et je saute sur le second thread ouvert, avant d'en ouvrir un de plus ^_^)

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

Discussions similaires

  1. Réponses: 7
    Dernier message: 23/06/2009, 09h33
  2. Réponses: 1
    Dernier message: 27/05/2009, 09h19
  3. IF sur une variable SHELL dans un bout de SQL
    Par nicolas.pailheret dans le forum Linux
    Réponses: 4
    Dernier message: 15/05/2009, 14h15
  4. Binding sur une variable static
    Par chris81 dans le forum Windows Presentation Foundation
    Réponses: 15
    Dernier message: 30/03/2009, 18h37
  5. [XSLT] Réutiliser une variable définie dans une boucle
    Par DelphLaga dans le forum XSL/XSLT/XPATH
    Réponses: 1
    Dernier message: 12/10/2006, 16h49

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