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 :

[TreeView] Rafraichissement des styles des items


Sujet :

Windows Presentation Foundation

  1. #1
    Membre régulier
    Profil pro
    Inscrit en
    Novembre 2007
    Messages
    163
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2007
    Messages : 163
    Points : 77
    Points
    77
    Par défaut [TreeView] Rafraichissement des styles des items
    Bonjour,

    J'ai un TreeView dont la source de donnée est un fichier xml. Le template est le même pour tous les items mais j'applique un style different selon le nom du node.

    J'ai créé un StyleSelector qui va chercher le style dans les resources du TreeView selon le nom du node.

    Au premier affichage, pas de problème.

    Par contre, mon appli permet de modifier les styles. Donc j'aimerais forcer le control à rafraichir les styles des items pour prendre en compte les modifications .

    Est-ce qu'il existe un moyen de forcer le rafraichissement des styles ?

    AL2000

  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 570
    Points
    3 570
    Par défaut
    Une manière de faire serait de binder dans tes style les elements à changer sur des dynamicresources. Et après, via code par exemple, changer ces ressources.

    Un exemple sera plus clair

    Dans ton fichier ressource
    Code XAML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    ...
     <SolidColorBrush x:Key="BackgroundBrush"
                             Color="Blue" />
            <Style x:Key="TextStyle" TargetType="{x:Type TextBlock}">
                <Setter Property="Background"
                        Value="{DynamicResource BackgroundBrush}" />
            </Style>
    ...

    Un textblock exemple :
    Code xaml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
     <TextBlock Style="{StaticResource TextStyle}" Width="100" Height="30" Text="Magie!" />

    Puis, dans ton code :
    Code C# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    this.Resources["BackgroundBrush"] = new SolidColorBrush(Colors.Red);
    Et la couleur du background est automatiquement changé.

  3. #3
    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 442
    Points
    4 442
    Par défaut
    bonjour al2000
    Bah tout depend de la methode que tu utilise pour "commuter" d'un StyleSelector à l'autre ( cela equivaut en fait à changer d'un StyleSelector à un autre)....
    Voici un exemple ou j'utilise un ComboBox et un click dessus sans code-behind.
    Le ComboBox store le "key" du StyleSelector dans sa prop Tag et propose un choix de 2 StyleSelectors.
    Le ItemContainerSelector est binde au champ Tag qui contient le "key" choisi.....
    Le StyleSelector choisi est rafraichi à la volee
    Au lieu d'un Combo ce pourrait etre une serie de choix proposes à l'user par CheckBoxes pour chaque StyleSelector ........

    Code-Behind des 2 StyleSelectors qui colorie un item "Node" suivant la valeur d'une prop data NodeColor (Yes ou Non ) dans StyleSelector1 ou StyleSelector2:
    Code c# : 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
     
    //StyleSelector 1 => choisit entre TreeViewItemStyle1 et TreeViewItemStyle2
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
     
    namespace WpfModifyStyleAtRuntimeCSharp
    {
        public class TreeViewItemStyleSelectorSwitchA : StyleSelector
        {
            public override Style SelectStyle(object item, DependencyObject container)
            {
                if (item != null && item is Node)
                {
                    Grid grd = ((WindowSwitchStyle)Application.Current.MainWindow).grd1;
                    Node nd = item as Node;
                    if (nd.NodeColor == "Yes")
                    {
                        if (grd != null)
                        {
                            return grd.FindResource("TreeViewItemStyle1") as Style;
                        }
                    }
                    else
                    {  
                        if (grd != null)
                        {
                            return grd.FindResource("TreeViewItemStyle2") as Style;
                        }
                    }
     
                }
                return null;
            }
        }
    }
    //StyleSelector 2 => choisit entre TreeViewItemStyle3 et TreeViewItemStyle4
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
     
    namespace WpfModifyStyleAtRuntimeCSharp
    {
        public class TreeViewItemStyleSelectorSwitchB : StyleSelector
        {
            public override Style SelectStyle(object item, DependencyObject container)
            {
                if (item != null && item is Node)
                {
                    Grid grd = ((WindowSwitchStyle)Application.Current.MainWindow).grd1;
                    Node nd = item as Node;
                    if (nd.NodeColor == "Yes")
                    {
                        if (grd != null)
                        {
                            return grd.FindResource("TreeViewItemStyle3") as Style;
                        }
                    }
                    else
                    {
                        if (grd != null)
                        {
                            return grd.FindResource("TreeViewItemStyle4") as Style;
                        }
                    }
     
                }
                return null;
            }
        }
    }
    code du class data utilise dans l'exemple :
    Code c# : 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
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections.ObjectModel;
     
    namespace WpfModifyStyleAtRuntimeCSharp
    {
     
     
        public class Node
        {
            private string _nodeColor; 
            private string _nodeName;
            public Node(string nd)
            {
                _nodeName = nd;
                _nodeColor = "Yes";
            }
     
            public string NodeName { get { return _nodeName; } }
            public string NodeColor 
            { get { return _nodeColor; }
              set { _nodeColor=value ; }
            }
        }
        public class ListNodes : ObservableCollection<Node>
        {
            public ListNodes() { }
        }
     
        public class GroupNode
        {
            private string _groupName;
            private ListNodes _nodes;
            public GroupNode(string d)
            {
                _groupName=d;
                _nodes = new ListNodes();
            }
            public string GroupName { get { return _groupName; } }
            public ListNodes Nodes
            {
                get { return _nodes; }
            }
         }
        public class ListGroupNodes : ObservableCollection<GroupNode>
        {
            public ListGroupNodes() { }
        }
     
        public class TreeViewNode : ObservableCollection<GroupNode>
        {
     
            public TreeViewNode()
            {
     
                Node itemNode;
                GroupNode itemGroupNode;
     
                   for (int j = 0; j < 4; ++j)
                    {
                        itemGroupNode = new GroupNode("Group" + j.ToString());
                        for (int k = 0; k < 10; k++)
                        {
                            if (k < 5)
                            { 
                                itemNode = new Node("Node" + k.ToString());
                                itemNode.NodeColor="Yes";
                            }
                            else
                            { 
                                itemNode = new Node("Node" + k.ToString());
                                itemNode.NodeColor = "No";
                            }
     
                            itemGroupNode.Nodes.Add(itemNode);
                        }
                        this.Add(itemGroupNode);
                    }
            }
     
        }
     
    }
    et code xaml du winform :
    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
    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
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
     
    <Window x:Class="WpfModifyStyleAtRuntimeCSharp.WindowSwitchStyle"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfModifyStyleAtRuntimeCSharp"
        Title="Switch StyleSelector" Height="300" Width="300">
        <Grid x:Name="grd1">
            <Grid.Resources>
                <!--les 2 StyleSelectors-->
                <local:TreeViewItemStyleSelectorSwitchA x:Key="tviASelector"/>
                <local:TreeViewItemStyleSelectorSwitchB x:Key="tviBSelector"/>
     
                <!--Style 1 & 2 du tviASelector-->
                <Style 
                    x:Key="TreeViewItemStyle1"  
                    TargetType="TreeViewItem">
                    <Setter Property="Foreground" Value="Navy"/>
                    <Setter Property="FontStyle" Value="Italic"/>
                </Style>
                <Style 
                    x:Key="TreeViewItemStyle2" 
                    TargetType="TreeViewItem">
                    <Setter Property="Foreground" Value="Green"/>
                    <Setter Property="FontWeight" Value="Bold"/>
                </Style>
                <!--Style 3 & 4 du tviBSelector-->
                <Style 
                    x:Key="TreeViewItemStyle3"  
                    TargetType="TreeViewItem">
                    <Setter Property="Foreground" Value="Magenta"/>
                    <Setter Property="FontStyle" Value="Italic"/>
                    <Setter Property="FontSize" Value="16"/>
                </Style>
                <Style 
                    x:Key="TreeViewItemStyle4" 
                    TargetType="TreeViewItem">
                    <Setter Property="Foreground" Value="Tomato"/>
                    <Setter Property="FontWeight" Value="Bold"/>
                    <Setter Property="FontSize" Value="16"/>
                </Style>
     
                <!--Les datas-->
     
                <local:TreeViewNode x:Key="MyList"/>
                <!--un simple HeaderTemplater-->
                <Style  
                    x:Key="RedHeaderTemplate" TargetType="{x:Type TextBlock }">
                    <Setter Property="Foreground" Value="Gold" />
                    <Setter Property="FontSize" Value="16" />
                    <Setter Property="FontWeight" Value="Bold" />
                    <Setter Property="TextWrapping" Value="Wrap" />
                </Style>
                <!--1er HierarchicalDataTemplate-->
                <HierarchicalDataTemplate
                    DataType= "{x:Type local:TreeViewNode}"
                    ItemsSource = "{Binding Path=ListGroupNodes}">
                    <TextBlock Text="{Binding Path=GroupName}"
                               Style="{StaticResource RedHeaderTemplate}"/>
                </HierarchicalDataTemplate>
                <!--2eme HierarchicalDataTemplate-->
                <HierarchicalDataTemplate
                    DataType= "{x:Type local:GroupNode}"
                    ItemsSource = "{Binding Path=Nodes}" >
                    <TextBlock Text="{Binding Path=GroupName}"
                               Style="{StaticResource RedHeaderTemplate}"/>
                </HierarchicalDataTemplate>
               <!--DataTemplate Node-->
                <DataTemplate
                    DataType= "{x:Type local:Node}">
                    <TextBlock Text="{Binding Path=NodeName}"/>
                </DataTemplate>
            </Grid.Resources>
     
            <Grid.RowDefinitions >
                <RowDefinition Height="*"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
            </Grid.RowDefinitions>
            <!-- ComboBox & StyleSelectors 1-2 defined somewhere else on your page -->
            <ComboBox 
                Grid.Row="0"
                x:Name="AvailableSelectors">
                <ComboBoxItem Tag="{x:Null}" IsSelected="True">None</ComboBoxItem>
                <ComboBoxItem Tag="{StaticResource tviASelector}">1</ComboBoxItem>
                <ComboBoxItem Tag="{StaticResource tviBSelector}">2</ComboBoxItem>
            </ComboBox>
            <StackPanel
                 Grid.Row="1">
                <TreeView 
                    x:Name="treeNodes" 
                    Height="100"
                    VirtualizingStackPanel.IsVirtualizing="True">
                    <TreeViewItem
                        ItemContainerStyleSelector="{Binding ElementName=AvailableSelectors, Path=SelectedItem.Tag}"
                        ItemsSource="{Binding Source={StaticResource MyList}}">
                        <TreeViewItem.Header>
                            <TextBlock 
                                Text="treeNodes"
                                Style="{StaticResource RedHeaderTemplate}">
                            </TextBlock>
                        </TreeViewItem.Header>
                    </TreeViewItem>
                    <TreeView.ItemContainerStyle>
                        <Style
                            TargetType="TreeViewItem">
                            <Setter Property="IsExpanded" 
                                    Value="True"/>
                        </Style>
                    </TreeView.ItemContainerStyle>
                </TreeView>
            </StackPanel>
        </Grid>
    </Window>
    Pas de code behind comme tu le vois , mis a part le code des 2 StyleSelectors bien entendu.....
    bon code............

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

Discussions similaires

  1. [WD17] manipulation des style des rubriques dans un etat
    Par vegetacherif dans le forum WinDev
    Réponses: 1
    Dernier message: 29/07/2013, 11h21
  2. Réponses: 19
    Dernier message: 20/12/2006, 10h15
  3. Gestion des majuscules des miniscules des accent
    Par issam16 dans le forum Access
    Réponses: 2
    Dernier message: 13/07/2006, 14h21

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