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 :

Utilisation d'un Converter selon une condition


Sujet :

Windows Presentation Foundation

  1. #1
    Membre actif
    Profil pro
    Inscrit en
    Juillet 2004
    Messages
    849
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2004
    Messages : 849
    Points : 295
    Points
    295
    Par défaut Utilisation d'un Converter selon une condition
    Bonjour,

    J'ai un élément d'un user control qui utilise un converter. "converterFather"
    Mais je souhaiterai que si le user control à sa propriété IsMother à true je souhaiterais utiliser le converter "converterMother"

    Comment faire ça le plus propre ?

    Merci beaucoup pour les pistes que vous m'accorderez.

  2. #2
    Membre expert
    Avatar de GuruuMeditation
    Homme Profil pro
    .Net Architect
    Inscrit en
    Octobre 2010
    Messages
    1 705
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : Belgique

    Informations professionnelles :
    Activité : .Net Architect
    Secteur : Conseil

    Informations forums :
    Inscription : Octobre 2010
    Messages : 1 705
    Points : 3 568
    Points
    3 568
    Par défaut
    Tu peux essayer avec un IMultiValueConverter, comme ici : http://stackoverflow.com/questions/1...erterparameter

    Ou alors un markup extension :


    http://www.codeproject.com/Articles/...er-and-StringF
    Microsoft MVP : Windows Platform

    MCPD - Windows Phone Developer
    MCPD - Windows Developer 4

    http://www.guruumeditation.net

    “If debugging is the process of removing bugs, then programming must be the process of putting them in.”
    (Edsger W. Dijkstra)

  3. #3
    Membre actif
    Profil pro
    Inscrit en
    Juillet 2004
    Messages
    849
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2004
    Messages : 849
    Points : 295
    Points
    295
    Par défaut
    J'essaye avec le IMultiValueConverter, mais je n'arrive pas à "binder" mon ancien paramètre

    Avant:
    Code XAML : Sélectionner tout - Visualiser dans une fenêtre à part
    <Border Name="bd" BorderBrush="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=2, AncestorType={x:Type ContentPresenter}}, Path=(ItemsControl.AlternationIndex),StringFormat=\{0\}, Converter={StaticResource posConvert}}" BorderThickness="5" CornerRadius="5" >

    Après:
    Code XAML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    <MultiBinding Converter="{StaticResource posConvert}">
       <Binding  ?????? />
       <Binding Path="MaxChoice" />
    </MultiBinding>

  4. #4
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    bonjour

    J'ai un élément d'un user control qui utilise un converter. "converterFather"
    Mais je souhaiterai que si le user control à sa propriété IsMother à true je souhaiterais utiliser le converter "converterMother"
    si bien compris le souci c'est mettre à jour la valeur d'un FrameworkElement child du UserControl quand une Dependency Property du UserConstrol IsMother change ....Via 2 converter (=> autrement un Multivalueconverter )....

    Il existe une autre facon d'employer un Multiconverter qui prends en entrée dans son tableau Values (props bindees) une reference à lui-meme,plus ta prop IsMother.....bindee à un Checkbox du form...

    Regarde sur ce lien MSDN intitule "WpfHowTo: Pass and use a Control in it's own ValueConverter for Convert/Convert​Back"qui renvoie vers un exemple code .zip ...
    http://www.google.fr/url?sa=t&rct=j&...99804247,d.d24

    bon code...

  5. #5
    Membre actif
    Profil pro
    Inscrit en
    Juillet 2004
    Messages
    849
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2004
    Messages : 849
    Points : 295
    Points
    295
    Par défaut
    En gros c'est ça.

    Mon control est dans une liste "ItemsControl", et j'ai besoin de connaitre sa position dans la liste, pour le convertir.
    Mais selon le nombre d’élément total de cette liste, mon converter ne doit pas faire le même calcul.

  6. #6
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    rebonjour

    Mon control est dans une liste "ItemsControl", et j'ai besoin de connaitre sa position dans la liste, pour le convertir.
    Mais selon le nombre d’élément total de cette liste, mon converter ne doit pas faire le même calcul
    La question a change du tout au tout !!!
    C'est un IMultiValueConvertir qui "opine" suivant l'index de la ItemCollection (ItemsControl.Items) ou de la vue de cette collection (ItemsControl.ItemSource) et le nbre d'element contenu dans l'une ou l'autre de ces 2 collections....

    Voici un Multiconverter qui se branche sur l' ItemsSource de l'ItemsControl dans son DataTemplate au niveau d'un control TextBlock( peut etre loge dans UserControl) binde sur la valeur convertie....
    L'exemple binde le textblock sur l'index de l'item courant(on pourrait renvoyer un brush ou tout autre type suivant le probleme à gerer)...
    Un 2eme textblock du DataTemplate est binde sur la prop Items.Count de celui-ci....
    Si on "opine" sur cette valeur Items.Count dans le MultiConverter elle est accessible grace à la variable collection.Count !!!
    code .cs du converter:
    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
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Data;
    using System.Globalization;
    using System.Windows.Controls;
    using System.Collections;
     
    namespace WpfAlternationItemsControl
    {
        public class GetIndexMultiConverter : IMultiValueConverter
        {
            public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
            {
                var ctx = values[1];
                if (ctx == null) return 0;
                var collection = (CollectionView)
                CollectionViewSource.GetDefaultView(ctx);
                var itemIndex = collection.IndexOf(values[0]);
     
                return  itemIndex.ToString();
            }
     
            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException("GetIndexMultiConverter_ConvertBack");
            }
        }
    }
    code xaml du 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
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
     
    <Window x:Class="WpfAlternationItemsControl.Window4"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfAlternationItemsControl"
            Title="Window3" Height="300" Width="300">
        <Window.Resources>
            <local:Persons x:Key="src"/>
            <local:GetIndexMultiConverter x:Key="GetIndexMultiConverter"/>
     
        </Window.Resources>
        <Grid >
            <ListBox  x:Name="lb" ItemsSource="{Binding Source={StaticResource src}}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel HorizontalAlignment="Center" Orientation="Horizontal" >
                            <TextBlock Panel.ZIndex="5" Margin="5" Text="{Binding ID}" HorizontalAlignment="Center" />
                            <TextBlock Margin="5" Text="{Binding Name}" HorizontalAlignment="Center" />
                            <TextBlock Margin="5" HorizontalAlignment="Center">
                                <TextBlock.Text>
                                    <MultiBinding Converter="{StaticResource GetIndexMultiConverter}" ConverterParameter="0">
                                            <Binding Path="."/>
                                            <Binding RelativeSource="{RelativeSource
                                            FindAncestor, AncestorType={x:Type ItemsControl}}"
                                            Path="ItemsSource"/>
                                    </MultiBinding>
                                </TextBlock.Text>
                            </TextBlock>
                            <TextBlock Margin="5" HorizontalAlignment="Center" 
                                       Text="{Binding ElementName=it, Path=Items.Count}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
     
            </ListBox>
        </Grid>
    </Window>
    code du class person de test :
    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
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Windows;
     
    namespace WpfAlternationItemsControl
     
    {
         public  class Person:INotifyPropertyChanged
        { 
             public Person()
            {
     
                ID = string.Empty;
                Name = string.Empty;
     
            }
             public Person(string pid, string pname)
                 : this()
             {
                 ID = pid;
                 Name =pname;
     
             }
             private string id;
             public string ID
            {
                get { return id; }
                set { id = value; RaisePropertyChanged("ID"); }
            }
     
            private string name;
            public string Name
            {
                get { return name; }
                set { name = value; RaisePropertyChanged("Name"); }
            }
     
     
     
            public event PropertyChangedEventHandler PropertyChanged;
             private void RaisePropertyChanged(string n)
             {
                 PropertyChangedEventHandler h = PropertyChanged;
                 if (h != null)
                     h(this, new PropertyChangedEventArgs(n));
             }
        }
        public class Persons:ObservableCollection<Person>
        {
            private Person p;
            public Persons()
            {
                for (int i = 1; i < 11; i++)
                {
     
     
                    p = new Person(i.ToString() , "Item" + i);
                    this.Add(p);
                }
            }
     
        }
    }
    bon code.........

  7. #7
    Membre actif
    Profil pro
    Inscrit en
    Juillet 2004
    Messages
    849
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2004
    Messages : 849
    Points : 295
    Points
    295
    Par défaut
    Merci beaucoup

  8. #8
    Membre actif
    Profil pro
    Inscrit en
    Juillet 2004
    Messages
    849
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2004
    Messages : 849
    Points : 295
    Points
    295
    Par défaut
    J'ai une dernière question, mon converter fonctionne.

    Je bind mes données sur la propriété BorderBrush de Border. Mais il ne se passe rien. Les bonnes valeurs apparaissent bien si j'utilise <TextBlock.Text>

    Code WPF : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     <Border.BorderBrush>
                        <MultiBinding Converter="{StaticResource posConvert}" ConverterParameter="0">
                            <Binding Path="."/>
                            <Binding RelativeSource="{RelativeSource
                                            FindAncestor, AncestorType={x:Type ItemsControl}}"
                                            Path="ItemsSource"/>
                            <Binding Path="MaxChoice"/>
                        </MultiBinding>
                    </Border.BorderBrush>

  9. #9
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    rebonjour
    Je bind mes données sur la propriété BorderBrush de Border. Mais il ne se passe rien. Les bonnes valeurs apparaissent bien si j'utilise <TextBlock.Text>
    Mais le converter poste tel quel renvoie l'index de l'item sous forme d'un string...pour le TextBlock car sa prop Text attends un type String....!!!


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
     return  itemIndex.ToString();
    Dans ton return tu dois renvoyer un type "Brush" car la prop Border.Brush de ton Border est de type Brush...
    Que tu dois recuperer quelque part dans le code du Converter ou la lui transmettre en xaml....

    Pour illustrer le propos voici le meme converter mais equipe d'une dependency property Borders de type List<Of SolidColorBrush> qui lui permet de recevoir la liste idoine...

    code .cs ConverterIndextoBrush
    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
     
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Data;
    using System.Globalization;
    using System.Windows.Media;
    using System.Windows;
    using System.Windows.Controls;
    namespace WpfAlternationItemsControl
    {
        public class GetIndexToBrushMultiConverter : DependencyObject , IMultiValueConverter
        {
            public GetIndexToBrushMultiConverter()
            {
                Borders = new List<SolidColorBrush>();
                Borders.Add(Brushes.Black); //brush par defaut
            }
            public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
            {
                var ctx = values[1];
                if (ctx == null) return 0;
     
                var collection = (CollectionView)
                CollectionViewSource.GetDefaultView(ctx);
                var itemIndex = collection.IndexOf(values[0]);
                if (itemIndex % Borders.Count == 0) //multiple 
                {
                    return Borders[0];
                }
                else // sinon l'index du brush est modulo Borders.Count
                {
                    return Borders[itemIndex % Borders.Count];
                }
     
            }
     
            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException("GetIndexMultiConverter_ConvertBack");
            }
     
     
     
            public List<SolidColorBrush > Borders
            {
                get { return (List<SolidColorBrush>)GetValue(BordersProperty); }
                set { SetValue(BordersProperty, value); }
            }
     
            // Using a DependencyProperty as the backing store for Borders.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty BordersProperty =
                DependencyProperty.Register("Borders", typeof(List< SolidColorBrush>),
                typeof(GetIndexToBrushMultiConverter), 
                new FrameworkPropertyMetadata (null));
     
     
     
        }
    }
    code xaml du 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
    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
     
    <Window x:Class="WpfAlternationItemsControl.Window5"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfAlternationItemsControl"
            Title="Window5" Height="300" Width="300">
        <Window.Resources>
            <local:Persons x:Key="src"/>
            <local:GetIndexToBrushMultiConverter x:Key="GetIndexMultiConverter"
                                                 >
                <local:GetIndexToBrushMultiConverter.Borders>
                    <SolidColorBrush   Color="Red" />
                    <SolidColorBrush   Color="DarkBlue"  />
                    <SolidColorBrush   Color="Yellow"  />
                    <SolidColorBrush   Color="LimeGreen"  />
                </local:GetIndexToBrushMultiConverter.Borders>
            </local:GetIndexToBrushMultiConverter> 
     
        </Window.Resources>
        <Grid >
            <ListBox  x:Name="lb" ItemsSource="{Binding Source={StaticResource src}}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel HorizontalAlignment="Center" Orientation="Horizontal" >
                            <TextBlock Panel.ZIndex="5" Margin="5" Text="{Binding ID}" HorizontalAlignment="Center" />
                            <TextBlock Margin="5" Text="{Binding Name}" HorizontalAlignment="Center" />
                            <Border 
                                BorderThickness="5">
                                <Border.BorderBrush>
                                    <MultiBinding Converter="{StaticResource GetIndexMultiConverter}" ConverterParameter="0">
                                        <Binding Path="."/>
                                        <Binding RelativeSource="{RelativeSource
                                            FindAncestor, AncestorType={x:Type ItemsControl}}"
                                            Path="ItemsSource"/>
                                    </MultiBinding>
                                </Border.BorderBrush>
                            </Border>
     
                            <TextBlock Margin="5" HorizontalAlignment="Center" 
                                       Text="{Binding ElementName=it, Path=Items.Count}"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
     
            </ListBox>
        </Grid>
    </Window>
    bon code....

  10. #10
    Membre actif
    Profil pro
    Inscrit en
    Juillet 2004
    Messages
    849
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Juillet 2004
    Messages : 849
    Points : 295
    Points
    295
    Par défaut
    Dans mon converter j'ai mis ça, mais toujours le même problème

    Code C# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    Color color = (Color)ColorConverter.ConvertFromString("#FF00FF");
                    SolidColorBrush brush = new SolidColorBrush(color);
                    return brush;

Discussions similaires

  1. Creation des autres fenetres selon une condition!!
    Par pointer dans le forum Delphi
    Réponses: 3
    Dernier message: 24/06/2006, 15h50
  2. Réponses: 8
    Dernier message: 05/05/2006, 16h33
  3. Affichage selon une condition dans un DBGRID !
    Par obon dans le forum Bases de données
    Réponses: 2
    Dernier message: 14/04/2006, 09h26
  4. Couleur de celulles de DBGRid selon une condition.
    Par abdelghani_k dans le forum Bases de données
    Réponses: 3
    Dernier message: 31/10/2005, 12h17
  5. Réponses: 5
    Dernier message: 23/02/2005, 09h43

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