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 :

XAML, togglebutton, styles et trigger


Sujet :

Windows Presentation Foundation

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Modérateur
    Avatar de sevyc64
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Janvier 2007
    Messages
    10 251
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Janvier 2007
    Messages : 10 251
    Par défaut XAML, togglebutton, styles et trigger
    Salut à tous, je galère encore pas mal en xaml.

    Contexte : appli bureau, WPF avec MVVM, développée sous VS2012, tous les écrans sont des usercontrols.

    Je dois rajouter, sur un écran, un contrôle à bascule qui va m'alimenter une variable dans le code (VB) qui sera certainement stockée dans la classe Application. Çà, je devrais arriver à le faire.
    Je voudrais que lors de la bascule, la couleur du texte de mon contrôle change, darkgrey lorsque inactif, red lorsque actif.
    A coté, j'ai un textblock, ainsi qu'un conteneur pour mettre en fils un autre écran. Je voudrais donc aussi que sur cette même bascule, la couleur de mon textblock, ainsi que la couleur de texte contenu dans l'écran fils (représenté par 2 textblock dans le datatemplate d'une listview) change de la même manière, couleur par défaut de leur style lorsque bascule inactive, red lorsque active.

    Pour des raisons de design, mon contrôle à bascule aura un visuel comme le textblock à coté. Je suis donc parti sur un togglebutton dont je redéfini le template. Mais je bloque sur le trigger du style. Je dois remonter jusqu'à la propriété IsChecked du toggle, mais comment faire :

    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
            <!-- Title View -->
            <TextBlock Grid.Column="1" Style="{StaticResource TitleStyle}"              <----- textblock qui sera à traiter aussi
                           Text="{Binding CurrentViewModel.Title}"/>
    
            <ToggleButton VerticalAlignment="Center" HorizontalAlignment="Center">
                <ToggleButton.Template>
                    <ControlTemplate TargetType="{x:Type ToggleButton}" >
                        <TextBlock  Text="Mode test">
                            <TextBlock.Style>
                                <Style BasedOn="{StaticResource TitleStyle}">
                                    <Style.Triggers>
                                        <Trigger Property="IsChecked" Value="True">        <------ c'est ici que je coince
                                            <Setter Property="Foreground" Value="Red" />
                                        </Trigger>
                                    </Style.Triggers>
                                </Style>
                            </TextBlock.Style>
                        </TextBlock>
                    </ControlTemplate>
                </ToggleButton.Template>
            </ToggleButton>
            
            <!-- PlaceHolder of Selected View -->
            <ContentControl Content="{Binding CurrentViewModel}" Grid.Row="1" />        <----- conteneur qui reçoie l'écran avec les autres textblock à traiter

    Optionnellement, j'aurais aimer aussi que le texte de mon toggle (et uniquement lui) soit en épaisseur normale et en italique lorsque inactif, et en non italique et en gras lorsque actif. Mais ça c'est déjà beaucoup plus accessoire.

  2. #2
    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

    Pour des raisons de design, mon contrôle à bascule aura un visuel comme le textblock à coté. Je suis donc parti sur un togglebutton dont je redéfini le template. Mais je bloque sur le trigger du style. Je dois remonter jusqu'à la propriété IsChecked du toggle, mais comment faire :
    Les Triggers d'un TextBlock se référent aux props du TextBlock lequel ne comporte aucune DP IsCheked sauf à remonter dans l'arbre visuel à quelque hypothétique parent ...

    Ensuite tu te fourvoie un peu il me semble ...
    Si tu veux que le ToggleButton "commande" la musique vu qu'il dispose d'une DP IsCheked fort à propos
    1/il suffit d'utiliser ses Triggers pour changer le Foreground du TextBlock "tbFaçade du ToggleButton"' , qui est un enfant ,donc sous son contrôle total .
    Mais ce faisant ton problème est à MOITIE RÉSOLU (basculer entre DarkGay & Red) pour le ToggleButton...

    2/L'autre MOITIE nécessite plus de travail c.à.d "basculer"
    - la DP Foreground du "tbTitle" bindé à une DP Title du VM tITLE ,laquelle est définie dans un Style
    donc hors de sa portée du chef d'orchestre Toggle...
    -idem pour les DP Foreground du "tbCommun et du ListBoxItem(un ListBox est pris pour exemple ci-après) lesquelles aussi sont définies dans des Styles...
    Pour résoudre ce cas épineux il faut recourir à un maître jacques ,intermédiaire obligé qui est une DP CLR dénommée "Change" de type Boolean dans le ViewModel ...
    Cette DP CLR est bindée à l’état IsChecked de maitre Toggle...
    Ensuite Via des DataTriggers qui pointent sur la valeur de la DP CLR "Change" on syNchronise la DP Foreground dans les des différents styles ...

    bref voici le code .vb:

    1/VM exemple:

    Code VB.NET : 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
    'data model
    Public Class Person
        Public Property Nom As String
        Public Property Age As Integer
    End Class
     
    'son viewmodel 
    Imports System.ComponentModel
    Imports System.Collections.ObjectModel
     
    Public Class PersonsViewModel
        Implements INotifyPropertyChanged
        Private m_title As String = "View1"
        Private m_change As Boolean
        Private m_persons As ObservableCollection(Of Person)
        Public Sub New()
            m_title = "View1"
            m_change = False
            Persons = New ObservableCollection(Of Person) From {
                New Person() With {.Nom = "Gil", .Age = 1},
                New Person() With {.Nom = "Dan", .Age = 2},
                New Person() With {.Nom = "John", .Age = 3}
                }
        End Sub
        Public Property Title As String
            Get
                Return m_title
            End Get
            Set(value As String)
                m_title = value
                Raise("Title")
            End Set
        End Property
     
        'DP CLR  maitre jaxques
        Public Property Change As Boolean
            Get
                Return m_change
            End Get
            Set(value As Boolean)
                m_change = value
                Raise("Change")
            End Set
        End Property
        Public Property Persons As ObservableCollection(Of Person)
            Get
                Return m_persons
            End Get
            Set(value As ObservableCollection(Of Person))
                m_persons = value
                Raise("Persons")
            End Set
        End Property
     
     
     
        Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
        Public Sub Raise(propertyName As String)
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
        End Sub
     
     
     
    End Class

    code xaml de la Fenêtre User:

    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
    <Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfToggle" 
        Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <local:PersonsViewModel x:Key="src"/>
            <DataTemplate x:Key="dtPerson" DataType="{x:Type local:Person}">
                <StackPanel Orientation="Horizontal" >
                    <TextBlock Margin="5" Text="{Binding Nom}"/>
                    <TextBlock Margin="5" Text="{Binding Age}"/>
                </StackPanel>
            </DataTemplate>
            <Style x:Key="styleTitle" TargetType="TextBlock" >
                <Setter Property="Foreground" Value="DarkBlue" />
                <Setter Property="FontFamily"  Value="Arial" />
                <Setter Property="FontSize" Value="20" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Change}"  Value="true">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
            <Style x:Key="styleTbFacade" TargetType="TextBlock" >
                <Setter Property="Foreground" Value="Gold" />
                <Setter Property="Background" Value="Beige" />
                <Setter Property="FontFamily"  Value="Arial" />
                <Setter Property="FontSize" Value="20" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Change}"  Value="true">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
            <Style x:Key="styleTbCommun" TargetType="TextBlock" >
                <Setter Property="Foreground" Value="CornflowerBlue" />
                <Setter Property="FontFamily"  Value="Times New Roman" />
                <Setter Property="FontSize" Value="14" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Change}"  Value="true">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
            <Style x:Key="styleItem" TargetType="ListBoxItem"  >
                <Setter Property="Foreground" Value="CornflowerBlue"  />
                <Setter Property="FontFamily" Value="Times New Roman" />
                <Setter Property="FontSize" Value="14" />
                <!--note que je remonte au DataContext du Grid-->
                <!--si tu charge le ViewModel par code dans une fenetre FN,il faut remonter au data de cette FN-->
                <Style.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}},Path=DataContext.Change, UpdateSourceTrigger=PropertyChanged}"  Value="true">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Window.Resources>
        <Grid DataContext="{Binding Source={StaticResource src}}">
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width ="100"></ColumnDefinition>
                <ColumnDefinition Width ="*"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <DockPanel Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2">
                <ToggleButton  
                Grid.Row="0" Grid.Column="0" Margin="10"
                FontFamily="Arial" FontSize="20"
                IsChecked="{Binding Path=Change}">
                    <ToggleButton.Content>
                        <Border BorderBrush="blue" BorderThickness="1.0" >
                            <TextBlock 
                                x:Name="tbFacade"
                                Style="{StaticResource styleTbFacade}"
                                Margin="5" Text="Change Color"/> 
                        </Border>
                    </ToggleButton.Content>
                </ToggleButton>
                <TextBlock
                Grid.Row="1" Grid.Column="0" Margin="10"
                x:Name="tbTbTitle"
                Style="{StaticResource styleTitle}"
                Text="{Binding  Path=Title,Mode=TwoWay}"/>
            </DockPanel>
     
            <TextBlock
                Grid.Row="1" Grid.Column="0"
                x:Name="tbCommun"
                Style="{StaticResource styleTbCommun}"
                Text="{Binding ElementName=lb, Path=SelectedItem.Nom,Mode=TwoWay}"/>
            <ListBox 
                Grid.Row="1" Grid.RowSpan="2" Grid.Column="1"
                x:Name="lb"
                SelectedIndex="0"
                IsSynchronizedWithCurrentItem="true"
                ItemsSource="{Binding Path=Persons}" 
                ItemTemplate="{StaticResource dtPerson}"
                ItemContainerStyle="{StaticResource styleItem}">
     
            </ListBox>
        </Grid>
    </Window>
    bon code...

  3. #3
    Modérateur
    Avatar de sevyc64
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Janvier 2007
    Messages
    10 251
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Janvier 2007
    Messages : 10 251
    Par défaut
    Bon, avec tes explications, même si je en suis pas certains d'avoir tout correctement compris , j'ai réussi à faire marcher le toggle et le textblock à coté.

    Par contre les textblock de la listview, je ne sais pas comment faire. Dans ton exemple, si j'ai bien suivi, à part le fait que tu utilise une listbox au lieu d'un listview, elle est surtout dans le même écran que le toggle.

    Moi dans mon cas, la listview se trouve sur un autre écran, indépendant, qui est chargé par le code dans le ContentControl de cet écran.
    Ok, pour remonter l'arbo des textblock pour retrouver le bon datacontext, mais ce n'est valable que sur le même écran, je vais pas pourvoir remonter dans l'autre écran conteneur ?

    L'écran qui contient les 2 autres textblock :
    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
    <UserControl ................>
        <!-- Root Layout -->
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="70"/>
            </Grid.RowDefinitions>
            <!-- Summary Combinations List -->
            <ListView x:Name="SummaryListView" 
                      SelectedItem="{Binding SelectedDataType}" 
                      ItemsSource="{Binding ExternalDataReport}" 
                      ItemContainerStyle="{StaticResource DefaultContainerItemStyle}" 
                      Style="{DynamicResource ListViewStyle1}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid HorizontalAlignment="Stretch">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="100"/>
                            </Grid.ColumnDefinitions>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Name}" Style="{StaticResource ListItemTextBlockStyle}"/>
                                <TextBlock Text="{Binding ViewModel.AssociationsCount, StringFormat=' ({0})'}" Style="{StaticResource ListItemTextBlockStyle}"/>
                            </StackPanel>
                            
                            ............................... 
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            
            .............................
        </Grid>
    </UserControl>

  4. #4
    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
    rebonjour

    j'ai faut observer que :
    Code XAML : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     <!--note que je remonte au DataContext du Grid-->
                <!--si tu charge le ViewModel par code dans une fenetre FN,il faut remonter au data de cette FN-->
    code exemple bis avec un ListView defini dans UserControl:

    1/code .vb du VM modifie avec raJout de la DP SelectedPerson(fins d'illustration)

    Code VB.NET : 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
    'son viewmodel 
    Imports System.ComponentModel
    Imports System.Collections.ObjectModel
     
    Public Class PersonsViewModel
        Implements INotifyPropertyChanged
        Private m_title As String = "View1"
        Private m_change As Boolean
        Private m_persons As ObservableCollection(Of Person)
        Private m_selectedperson As Person
        Public Sub New()
            m_title = "View1"
            m_change = False
            m_selectedperson = Nothing
            Persons = New ObservableCollection(Of Person) From {
                New Person() With {.Nom = "Gil", .Age = 1},
                New Person() With {.Nom = "Dan", .Age = 2},
                New Person() With {.Nom = "John", .Age = 3}
                }
        End Sub
        Public Property Title As String
            Get
                Return m_title
            End Get
            Set(value As String)
                m_title = value
                Raise("Title")
            End Set
        End Property
        'DP CLR  maitre jaxques
        Public Property Change As Boolean
            Get
                Return m_change
            End Get
            Set(value As Boolean)
                m_change = value
                Raise("Change")
            End Set
        End Property
        'RAJOUT DP SelectedPerson
        Public Property SelectedPerson As Person
            Get
                Return m_selectedperson
            End Get
            Set(value As Person)
                m_selectedperson = value
                Raise("SelectedPerson")
            End Set
        End Property
        Public Property Persons As ObservableCollection(Of Person)
            Get
                Return m_persons
            End Get
            Set(value As ObservableCollection(Of Person))
                m_persons = value
                Raise("Persons")
            End Set
        End Property
     
     
     
        Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
        Public Sub Raise(propertyName As String)
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
        End Sub
     
     
     
    End Class

    2/ code xaml du UserControl container de la ListView:

    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
    <UserControl x:Class="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">
        <!-- Root Layout -->
        <UserControl.Resources>
            <Style x:Key="DefaultContainerItemStyle" TargetType="ListViewItem">
                <Setter Property="Foreground" Value="Black"  />
                <Setter Property="FontFamily" Value="Arial" />
                <Setter Property="FontSize" Value="14" />
               <!--le ViewModel etant assigné par code dans la fenetre FN Wondow2,il faut remonter--> 
               <!--au datacontext de cette FN-->
                <Style.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}},Path=DataContext.Change, UpdateSourceTrigger=PropertyChanged}"  Value="true">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
            <Style x:Key="ListItemTextBlockStyle" TargetType="TextBlock" >
                <Setter Property="Foreground" Value="CornflowerBlue"  />
                <Setter Property="FontFamily" Value="Times New Roman" />
                <Setter Property="FontSize" Value="14" />
                <!--IDEM-->
                <!--le ViewModel etant assigné par code dans la fenetre FN Wondow2,il faut remonter-->
                <!--au datacontext de cette FN-->
                <Style.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext.Change, UpdateSourceTrigger=PropertyChanged}"  Value="true">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </UserControl.Resources>
        <Grid>
            <!-- Summary Combinations List -->
            <ListView 
                x:Name="SummaryListView" 
                SelectedIndex="0"
                SelectedItem="{Binding SelectedPerson}" 
                ItemsSource="{Binding Persons}" 
                ItemContainerStyle="{StaticResource DefaultContainerItemStyle}" 
                      >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid HorizontalAlignment="Stretch">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="100"/>
                            </Grid.ColumnDefinitions>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock 
                                                                    Margin="10"
                                    Style="{StaticResource ListItemTextBlockStyle}"
                                    Text="{Binding Nom}" />
                                <TextBlock 
                                    Margin="10"
                                    Style="{StaticResource ListItemTextBlockStyle}"
                                    Text="{Binding Age}" />
                            </StackPanel>
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </UserControl>

    3/ code xaml du Form User:

    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
    <Window x:Class="Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfToggle"
        Title="Window2" Height="350" Width="525">
        <Window.Resources>
            <DataTemplate x:Key="dtPerson" DataType="{x:Type local:Person}">
                <StackPanel Orientation="Horizontal" >
                    <TextBlock Margin="5" Text="{Binding Nom}"/>
                    <TextBlock Margin="5" Text="{Binding Age}"/>
                </StackPanel>
            </DataTemplate>
            <Style x:Key="styleTitle" TargetType="TextBlock" >
                <Setter Property="Foreground" Value="DarkBlue" />
                <Setter Property="FontFamily"  Value="Arial" />
                <Setter Property="FontSize" Value="20" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Change}"  Value="true">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
            <Style x:Key="styleTbFacade" TargetType="TextBlock" >
                <Setter Property="Foreground" Value="Gold" />
                <Setter Property="Background" Value="Beige" />
                <Setter Property="FontFamily"  Value="Arial" />
                <Setter Property="FontSize" Value="20" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Change}"  Value="true">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
            <Style x:Key="styleTbCommun" TargetType="TextBlock" >
                <Setter Property="Foreground" Value="CornflowerBlue" />
                <Setter Property="FontFamily"  Value="Times New Roman" />
                <Setter Property="FontSize" Value="14" />
                <Setter Property="HorizontalAlignment" Value="Center" />
                <Setter Property="VerticalAlignment" Value="Top" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Change}"  Value="true">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Window.Resources>
        <Grid >
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto"></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width ="100"></ColumnDefinition>
                    <ColumnDefinition Width  ="100"></ColumnDefinition>
                    <ColumnDefinition Width ="*"></ColumnDefinition>
                </Grid.ColumnDefinitions>
            <DockPanel Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3">
                <ToggleButton  
                Margin="10"
                FontFamily="Arial" FontSize="20"
                IsChecked="{Binding Path=Change}">
                    <ToggleButton.Content>
                        <Border BorderBrush="blue" BorderThickness="1.0" >
                            <TextBlock 
                                x:Name="tbFacade"
                                Style="{StaticResource styleTbFacade}"
                                Margin="5" Text="Change Color"/>
                        </Border>
                    </ToggleButton.Content>
                </ToggleButton>
                <TextBlock
                Margin="10"
                x:Name="tbTbTitle"
                Style="{StaticResource styleTitle}"
                Text="{Binding  Path=Title,Mode=TwoWay}"/>
            </DockPanel>
            <TextBlock
                Grid.Row="1" Grid.Column="0"
                x:Name="tbCommun1"
                Style="{StaticResource styleTbCommun}"
                Text="{Binding  Path=SelectedPerson.Nom,Mode=TwoWay}"/>
            <TextBlock
                Grid.Row="1" Grid.Column="1"
                x:Name="tbCommun2"
                Style="{StaticResource styleTbCommun}"
                Text="{Binding  Path=SelectedPerson.Age,Mode=TwoWay}"/>
            <ContentControl 
                Grid.Row="1"  Grid.Column="2"
                >
                <ContentControl.Content>
                    <local:UserControl1></local:UserControl1>
                </ContentControl.Content>
            </ContentControl>
     
        </Grid>
    </Window>
    & son crucial code behind .vb:

    Code VB.NET : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    Public Class Window2
        Private vm As New PersonsViewModel
        Public Sub New()
     
            ' Cet appel est requis par le concepteur.
            InitializeComponent()
     
            ' Ajoutez une initialisation quelconque après l'appel InitializeComponent().
            Me.DataContext = vm
        End Sub
    End Class
    bon code...

  5. #5
    Modérateur
    Avatar de sevyc64
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Janvier 2007
    Messages
    10 251
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Janvier 2007
    Messages : 10 251
    Par défaut
    Bon, j'ai pas mal batailler, mais ça semble marcher.

    D'abords pour définir la Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged, car elle est déjà défini dans le framework MVVM que j'utilise mais de type IObservable, pas INotify.
    En fait je n'en ai pas besoin, c'est déjà fait correctement dans le MVVM.

    J'ai réussi à trouver en mettant l'AncestorLevel à 2 dans le style redéfini des textblock des items de la listview. En effet, comme tous mes écrans sont des usercontrols, il fallait rechercher le usercontrol parent du usercontrol actuel, donc niveau 2

    Me reste plus qu'à traduire ça dans le code de production. J'ai tellement bidouiller le mien qu'il ne ressemble à grand chose.

  6. #6
    Modérateur
    Avatar de sevyc64
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Janvier 2007
    Messages
    10 251
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Janvier 2007
    Messages : 10 251
    Par défaut
    Ca a été intégré au code de production, les tests sont concluant. C'est prêt à être diffusé avec la prochaine version.


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

Discussions similaires

  1. [WPF] Styles et triggers
    Par zenico64 dans le forum C#
    Réponses: 4
    Dernier message: 25/03/2014, 20h27
  2. Style dans le Generic.xaml pour un CustomControl d'une bibliothéque de classe
    Par olsimare dans le forum Windows Presentation Foundation
    Réponses: 9
    Dernier message: 21/06/2008, 22h35
  3. [WPF][Resources & styles] récupération d'un style xaml en C#?
    Par bakonu dans le forum Général Dotnet
    Réponses: 3
    Dernier message: 13/11/2007, 15h30
  4. Generateur de Forms depuis un fichier Xml..Style XAML
    Par sacofan dans le forum VB 6 et antérieur
    Réponses: 4
    Dernier message: 27/11/2006, 16h10

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