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 :

changement de couleur police listview


Sujet :

C#

  1. #1
    Membre actif Avatar de marsupilami34
    Profil pro
    Inscrit en
    Juin 2005
    Messages
    574
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2005
    Messages : 574
    Points : 258
    Points
    258
    Par défaut changement de couleur police listview
    Bonjour à tous,

    J'ai une listview WPF pour laquelle je cherche, en fonction d'un certain critere d'ajouter un élément dans ma liste (bleu ou rouge).
    Mais soit tout est bleu, soit tout est rouge.

    Voici le code que j'ai réalisé

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
            private void AddBleuString Mission)
            {
                ListViewDialogue.FontSize = 15;
                ListViewDialogue.FontStyle = FontStyles.Italic;
                ListViewDialogue.Foreground = Brushes.Blue;
                ListViewDialogue.FontFamily = new FontFamily("Tahoma");
                ListViewDialogue.Items.Add("J'ai écrit en bleu");
            }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
            private void AddRouge(String Mission)
            {
                ListViewDialogue.FontSize = 15;
                ListViewDialogue.FontStyle = FontStyles.Normal;
                ListViewDialogue.Foreground = Brushes.Red;
                ListViewDialogue.FontFamily = new FontFamily("Tahoma");
                ListViewDialogue.Items.Add("J'ai écrit en rouge");
            }
    Faut-il utiliser autre qu'une listView ? Mais en lisant dans certains forum, ils privilégient la ListView

    Quelqu'un pourrait il m'aider svp ?

    Merci d'avance pour votre aide précieuse

    Marsup

  2. #2
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 065
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 065
    Points : 4 229
    Points
    4 229
    Par défaut
    Il faut que toutes la liste soit en bleu ou rouge, ou tu peux avoir les 2 dans la même liste.
    Perso j'utiliserai un valueconverter pour la couleur du texte, tu peux crée un objet qui contient ton texte et une propriété couleur que tu bind à la listview et ton value converter utilisera cette propriété pour changer la couleur du texte.

  3. #3
    Membre confirmé Avatar de Flow_75
    Femme Profil pro
    Ingénieure
    Inscrit en
    Mai 2005
    Messages
    1 096
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 40
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieure
    Secteur : Transports

    Informations forums :
    Inscription : Mai 2005
    Messages : 1 096
    Points : 633
    Points
    633
    Par défaut
    Bonjour,

    Tu peux utiliser une listbox sans soucis.

    Il faut personnaliser l'evenement DrawItem et mettre la propriété DrawMode à OwnerDrawFixed

    par exemple :

    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
    private void lb_Segments_DrawItem( object sender, DrawItemEventArgs e )
            {
                if(e.Index == -1)
                    return;
     
                Element theSegment = lb_Segments.Items[e.Index] as Element;
     
                    if(theSegment.Valid)
                    {
                        e.Graphics.FillRectangle( Brushes.DarkGreen, e.Bounds );
                        e.Graphics.DrawString( theSegment.ToString(), lb_Segments.Font, Brushes.White, e.Bounds );
                    }
                    else
                    {
                        e.DrawFocusRectangle();
                        e.Graphics.DrawString( theSegment.ToString(), lb_Segments.Font, Brushes.White, e.Bounds );
                    }
                }
                else
                {
                    if(theSegment.Valid)
                    {
                        e.Graphics.FillRectangle( Brushes.LightGreen, e.Bounds );
                    }
                    e.Graphics.DrawString( theSegment.ToString(), lb_Segments.Font, lb_Segments.ForeColor.ToBrush(), e.Bounds );
                }
            }

  4. #4
    Membre actif Avatar de marsupilami34
    Profil pro
    Inscrit en
    Juin 2005
    Messages
    574
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2005
    Messages : 574
    Points : 258
    Points
    258
    Par défaut
    Merci beaucoup Flow_75
    Par contre j'ai une erreur au niveau d Element. Faut-il rajouter un using paticulier ?

  5. #5
    Membre confirmé Avatar de Flow_75
    Femme Profil pro
    Ingénieure
    Inscrit en
    Mai 2005
    Messages
    1 096
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 40
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieure
    Secteur : Transports

    Informations forums :
    Inscription : Mai 2005
    Messages : 1 096
    Points : 633
    Points
    633
    Par défaut
    En faite, Element, c'est mon objet à moi.

    tu peux creer un objet et le mettre dans ta liste :

    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
     
    public class Elem
    {
        public Elem(string _Text, bool _bIsRed)
        {
                 Text = _Text;
                 bIsRes = _bIsRed;
        }
     
     
        public string Text {get;set;}
        public bool bIsRed {get;set;}
     
        public override string ToString()
        { 
                return Text;
         }
    }
    Cet element, tu le rajoutes à chaque fois dans ta liste.

    Dans le DrawItem, tu recupere l'element correspondant, et tu mets rouge ou vert

  6. #6
    Membre actif Avatar de marsupilami34
    Profil pro
    Inscrit en
    Juin 2005
    Messages
    574
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2005
    Messages : 574
    Points : 258
    Points
    258
    Par défaut
    Je ne suis pas sur d'avoir tout compris.

    Ce que j'ai compris, c'est qu'il faillait créer l'evenement DrawItem.
    Lorsque je vais insérer un élément dans ma listbox, ca va déclencher cet évenement. (si j'ai bien compris)

    Et après je suis perdu
    Je ne sais pas ce que c'est segment.valid et je ne vois pas ou mettre mon critere :-(
    Mais le DrawItemEventArgs n'est pas reconnu.

  7. #7
    Membre confirmé Avatar de Flow_75
    Femme Profil pro
    Ingénieure
    Inscrit en
    Mai 2005
    Messages
    1 096
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 40
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieure
    Secteur : Transports

    Informations forums :
    Inscription : Mai 2005
    Messages : 1 096
    Points : 633
    Points
    633
    Par défaut
    En faite, segment, c'est une classe que j'ai réalisé moi meme donc, tu l'oublies c'est normal que la définition tu ne l'as pas.



    J'ai modifié mon code en conséquence.

    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
     
     
    private void foo()
    {
    ... ...
     
    lb_Segments.Items.Add( new Elem("Text in red", true /* cet element sera rouge */));
    lb_Segments.Items.Add( new Elem("Text in blue", false /* cet element sera bleu */));
    ... ...
    }
     
    private void lb_Segments_DrawItem( object sender, DrawItemEventArgs e )
            {
                if(e.Index == -1)
                    return;
     
                Elem theElem = lb_Segments.Items[e.Index] as Elem; // ici, tu récuperes l'element dans la liste
     
                    if(theElem.bIsRed)
                    {
                        e.Graphics.FillRectangle( Brushes.Red, e.Bounds );
                        e.Graphics.DrawString( theElem.Text, lb_Segments.Font, Brushes.White, e.Bounds );
                    }
                    else
                    {
                        e.Graphics.FillRectangle( Brushes.Blue, e.Bounds );
                        e.Graphics.DrawString(theElem.Text , lb_Segments.Font, Brushes.White, e.Bounds );
                    }
                }

  8. #8
    Membre actif Avatar de marsupilami34
    Profil pro
    Inscrit en
    Juin 2005
    Messages
    574
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2005
    Messages : 574
    Points : 258
    Points
    258
    Par défaut
    Ok
    J'ai presque compris :-)

    Par contre j'ai des erreurs toujours

    Nom : ps.jpg
Affichages : 79
Taille : 56,9 Ko

  9. #9
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 065
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 065
    Points : 4 229
    Points
    4 229
    Par défaut
    En wpf c'est pas mieux d'utiliser un IValueConverter plutôt que s'amuser à dessiner en code, c'est un peu la philosophie de WindowsForms ça.

    Exemple simple à toi de le modifier pour ton cas, si t'as besoin que de 2 couleurs tu peux utiliser un boolean et renvoyer bleu ou rouge suivant son état :
    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
    24
    25
    26
    27
    28
    29
    <Window x:Class="ColorConverter.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:ColorConverter"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">
        <Window.Resources>
            <local:ColorValueConverter x:Key="ColorValueConverter"></local:ColorValueConverter>
        </Window.Resources>
     
        <StackPanel>
            <ListView x:Name="lstColors" Height="200" ItemsSource="{Binding Datas}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding Name}" Foreground="{Binding Color, Converter={StaticResource ColorValueConverter}}"></TextBlock>
                        </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <StackPanel Orientation="Horizontal">
                <Button Margin="10" Click="Button_Click">Add Blue</Button>
                <Button Margin="10" Click="Button_Click_1">Add Red</Button>
                <Button Margin="10" Click="Button_Click_2">Add Green</Button>
            </StackPanel>
        </StackPanel>
    </Window>

    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
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    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;
     
    namespace ColorConverter
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public ObservableCollection<Data> Datas { get; set; }
            public MainWindow()
            {
                InitializeComponent();
                Datas = new ObservableCollection<Data>();
                Datas.Add(new Data() { Color = Colors.Brown, Name = "marron" });
                this.DataContext = this;
            }
     
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                Datas.Add(new Data() { Color = Colors.Blue, Name = "bleu" });
            }
     
            private void Button_Click_1(object sender, RoutedEventArgs e)
            {
                Datas.Add(new Data() { Color = Colors.Red, Name = "red" });
            }
     
            private void Button_Click_2(object sender, RoutedEventArgs e)
            {
                Datas.Add(new Data() { Color = Colors.Green, Name = "green" });
            }
        }
    }
    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
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Text;
    using System.Windows.Data;
    using System.Windows.Media;
     
    namespace ColorConverter
    {
        public class ColorValueConverter :IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value is Color)
                {
                    return new SolidColorBrush((Color)value);
                }
                return null;
            }
     
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new Exception("The method or operation is not implemented.");
            }
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows.Media;
     
    namespace ColorConverter
    {
       public class Data
        {
            public string Name { get; set; }
            public Color Color { get; set; }
        }
    }

  10. #10
    Membre confirmé Avatar de Flow_75
    Femme Profil pro
    Ingénieure
    Inscrit en
    Mai 2005
    Messages
    1 096
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 40
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieure
    Secteur : Transports

    Informations forums :
    Inscription : Mai 2005
    Messages : 1 096
    Points : 633
    Points
    633
    Par défaut
    Alors, désolé, j'avais pas vu que c'etait du WPF.

  11. #11
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 065
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 065
    Points : 4 229
    Points
    4 229
    Par défaut
    Citation Envoyé par Flow_75 Voir le message
    Alors, désolé, j'avais pas vu que c'etait du WPF.
    Je me disais , c'est peut être pour ça que ton exemple ne marchait pas chez lui.

  12. #12
    Membre actif Avatar de marsupilami34
    Profil pro
    Inscrit en
    Juin 2005
    Messages
    574
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2005
    Messages : 574
    Points : 258
    Points
    258
    Par défaut
    Merci pour vos aides

    Cela dit j'ai encore une erreur à la compil.


    Nom : erreur.png
Affichages : 54
Taille : 20,6 Ko


    Pourtant j'ai bien créé mes classes :-(

  13. #13
    Expert confirmé

    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2010
    Messages
    2 065
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Novembre 2010
    Messages : 2 065
    Points : 4 229
    Points
    4 229
    Par défaut
    Le
    Code XAML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
        <Window.Resources>
            <local:ColorValueConverter x:Key="ColorValueConverter"></local:ColorValueConverter>
        </Window.Resources>

    est fonctionnel, tu as peut être pas le bon namespace

Discussions similaires

  1. Réponses: 4
    Dernier message: 22/04/2013, 19h30
  2. Changement de couleur : Police>Attribut
    Par shawn31 dans le forum Word
    Réponses: 2
    Dernier message: 16/01/2012, 01h08
  3. Pas de changement de couleur au clic dans une ListView
    Par profecie dans le forum Composants graphiques
    Réponses: 2
    Dernier message: 02/11/2011, 17h57
  4. changement couleur polices plage avec liste
    Par michel13 dans le forum Macros et VBA Excel
    Réponses: 11
    Dernier message: 17/04/2008, 18h08
  5. Changement de couleur de police sur une partie d'un caption
    Par kobe dans le forum Composants VCL
    Réponses: 3
    Dernier message: 11/07/2005, 10h18

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