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 :

Modifier Control Template dans le code Behind WPF/C#


Sujet :

C#

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2014
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Janvier 2014
    Messages : 15
    Points : 16
    Points
    16
    Par défaut Modifier Control Template dans le code Behind WPF/C#
    Bonjour chers amis développeurs;

    dans mon application j'ai un ResourceDictionary " DesignerItem" où je de définie un Control Template "<ControlTemplate x:Key="ConnectorDecoratorTemplate" TargetType="{x:Type Control}">" , ce Control Template me permet d'avoir des points sur mes objets de type "DesignerItem" pour tracer des lignes entre ces point par la suite. Pour cela ce control template est appéllé dans le style définie pour les objets "DesignerItem".

    ce que je veux faire maintenant c'est de pourvoir définir ou modifier le Control template"<ControlTemplate x:Key="ConnectorDecoratorTemplate" TargetType="{x:Type Control}">" dans le code source codeBehind car le nombre de point qui permet de dessiner une ligne est dynamique, chaque objet a nombre différents de points... le nombre de points qui vont être représentes par le control Template n'est connu que lorsque l’utilisateur fait un drop d'un objet sur un canvas, donc c'est a ce moments la que je veux intervenir pour modifier le controle Template pour avoir les points sur cet objet !!.

    je ne sais pas si cela est faisable ou pas ??? :'( ... je ne sais pas si je dois parser du code xaml dans mon control template ou comment je dois faire ......

    SVP, aidez moi !!

    voila mon code XAML


    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
    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:sys="clr-namespace:System;assembly=mscorlib"
                        xmlns:s="clr-namespace:DiagramDesigner"
                        xmlns:c="clr-namespace:DiagramDesigner.Controls">
     
        <!-- Connector Style -->
    	<!-- les Connector son les points qui nous permet des tracer les lignes-->
        <Style TargetType="{x:Type s:Connector}">
            <Setter Property="Width" Value="8"/>
            <Setter Property="Height" Value="8"/>
            <Setter Property="Cursor" Value="Cross"/>
            <Setter Property="SnapsToDevicePixels" Value="true"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type s:Connector}">
                        <Grid >
                            <!-- transparent extra space makes connector easier to hit -->
                            <!--c un carrer qui nous permet de dessiner la line entre les object-->
    						<Rectangle Fill="red" Margin="-2"/>
                            <Rectangle Fill="Red" StrokeThickness="5" Stroke="#AA000080"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
     
     
        <!--
        la partie suivante c'est la partie qui me me pose un probleme,
        c'est la partie que je veux la modifer a partir du code source 
        -->
     
        <!-- ConnectorDecoratorTemplate Default Template -->
     
     
        <ControlTemplate  x:Key="ConnectorDecoratorTemplate" TargetType="{x:Type Control}">
     
            <Grid x:Name="LesPointDeConnexion"><!-- les point qui me permet de tracer des lignes-->
                    <Grid.RowDefinitions>
                        <RowDefinition Height="0.5*"/>
                        <RowDefinition Height="0.5*"/>
                    </Grid.RowDefinitions>
                <s:Connector  Orientation="Left"  VerticalAlignment="Center" HorizontalAlignment="Left" Margin="5" Grid.Row="0"/>
                <s:Connector  Orientation="Left"  VerticalAlignment="Center" HorizontalAlignment="Left" Margin="5" Grid.Row="1"/>
     
                </Grid>
        </ControlTemplate>
     
     
        <!-- DesignerItem Style -->
        <Style  TargetType="{x:Type s:DesignerItem}">
            <Setter Property="MinWidth" Value="10"/>
            <Setter Property="MinHeight" Value="10"/>
            <Setter Property="SnapsToDevicePixels" Value="True"/>        
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type s:DesignerItem}">
                        <Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
     
                            <!-- PART_DragThumb -->
                            <c:DragThumb x:Name="PART_DragThumb" 
                                         Cursor="SizeAll"/>
     
                            <!-- PART_ResizeDecorator -->
                            <Control x:Name="PART_ResizeDecorator" 
                                     Visibility="Collapsed"
                                     Template="{StaticResource ResizeDecoratorTemplate}"/>
     
                            <!-- PART_ContentPresenter -->
                            <ContentPresenter x:Name="PART_ContentPresenter"
                                              HorizontalAlignment="Stretch"
                                              VerticalAlignment="Stretch"
                                              Content="{TemplateBinding ContentControl.Content}"
                                              Margin="{TemplateBinding ContentControl.Padding}"/>
     
     
                            <!-- PART_ConnectorDecorator -->
                            <Control x:Name="PART_ConnectorDecorator"
                                     Visibility="Visible"
                                     Template="{StaticResource ConnectorDecoratorTemplate}"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <DataTrigger Value="True" Binding="{Binding RelativeSource={RelativeSource Self},Path=IsGroup}">
                                <Setter TargetName="PART_DragThumb" Property="Visibility" Value="Collapsed"/>
                            </DataTrigger>
                            <MultiDataTrigger>
                                <MultiDataTrigger.Conditions>
                                    <Condition Value="True" Binding="{Binding RelativeSource={RelativeSource Self},Path=IsSelected}"/>
                                    <Condition Value="{x:Static sys:Guid.Empty}" Binding="{Binding RelativeSource={RelativeSource Self},Path=ParentID}"/>
                                </MultiDataTrigger.Conditions>
                                <Setter TargetName="PART_ResizeDecorator" Property="Visibility" Value="Visible"/>
                            </MultiDataTrigger>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Setter TargetName="PART_ConnectorDecorator" Property="Visibility" Value="Visible"/>
                            </Trigger>
                            <DataTrigger Value="True" Binding="{Binding RelativeSource={RelativeSource Self},Path=IsDragConnectionOver}">
                                <Setter TargetName="PART_ConnectorDecorator" Property="Visibility" Value="Visible"/>
                            </DataTrigger>
                            <DataTrigger Value="True" Binding="{Binding RelativeSource={RelativeSource Self},Path=IsGroup}">
                                <Setter TargetName="PART_ConnectorDecorator" Property="Visibility" Value="Hidden"/>
                            </DataTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
     
    </ResourceDictionary>

    Donc ce que je veux est de modifier le control Template qui porte x:Key="ConnectorDecoratorTemplate" dans le code source pour pouvoir l'adapter selon le nombre de point de l'objet.

    En fichier attaché une image qui représente le résultat actuel.

    Merci bien mes chers amis
    Images attachées Images attachées  

  2. #2
    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
    1/Si tu veux modifier ton ControlTemplate pour ajouter des controls Connector au Grid il faut que le grid porte un x:name suivant cette syntaxe impitoyable "PART_nom"...
    2/Ensuite on accede à chaque Control qui utilise ton ControlTemplate pour "grabber"(recuperer)son ControlTemplate et retrouver le Grid...!!!
    3/Une fois le grid recupere via son part_name on peut lui ajouter des connecteurs ....

    code exemple xaml:
    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
    <Window x:Class="WpfControlTemplateByCode.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfControlTemplateByCode" 
            Title="MainWindow" Height="350" Width="525">
        <StackPanel
            x:Name="pnl"
            MouseDown="pnl_MouseDown"
         >
            <DockPanel >
                <local:Connector
                    x:Name="con1"
                    Margin="25"
                    Width="59"
                    Height="50">
                </local:Connector>
                <TextBlock 
                    x:Name="tb"
                    Margin="25"
                    Background="LightBlue" >
                </TextBlock>
            </DockPanel>
     
            <local:MyControl
                x:Name="ctrl"
                Margin="15"
     
                Template="{StaticResource ConnectorDecoratorTemplate}">
            </local:MyControl>
        </StackPanel>
    </Window>
    code behind .cs:
    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
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
     
    namespace WpfControlTemplateByCode
    {
        /// <summary>
        /// Logique d'interaction pour MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
     
            private void pnl_MouseDown(object sender, MouseButtonEventArgs e)
            {
                int indexRow;
                RowDefinition rowdef;
                Connector cn; 
     
                Grid grd = ctrl.Template.FindName("PART_LesPointDeConnexion", ctrl) as Grid;
     
                rowdef = new RowDefinition();
                rowdef.Height = new GridLength(0.5,GridUnitType.Auto);
                grd.RowDefinitions.Add(rowdef);
                indexRow = grd.RowDefinitions.Count - 1;
     
                cn = new Connector();
                cn.Style = this.FindResource("styleCon") as Style;
                cn.VerticalAlignment = VerticalAlignment.Bottom;
                cn.HorizontalAlignment = HorizontalAlignment.Left;
                grd.Children.Add(cn);
                Grid.SetColumn(cn, 0);
                Grid.SetRow(cn, indexRow);
     
                rowdef = new RowDefinition();
                rowdef.Height = new GridLength(0.5, GridUnitType.Auto);
                grd.RowDefinitions.Add(rowdef);
                indexRow = grd.RowDefinitions.Count - 1; 
     
                cn = new Connector();
                cn.Style = this.FindResource("styleCon") as Style; 
                cn.VerticalAlignment = VerticalAlignment.Bottom;
                cn.HorizontalAlignment = HorizontalAlignment.Right ;
                grd.Children.Add(cn);
                Grid.SetColumn(cn, 1);
                Grid.SetRow(cn, indexRow);
     
                tb.Text = indexRow.ToString() ;
     
            }
     
        }
    }
    bon code...

  3. #3
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2014
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Janvier 2014
    Messages : 15
    Points : 16
    Points
    16
    Par défaut
    Merci infiniment monsieur Mabrouki

  4. #4
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2014
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Janvier 2014
    Messages : 15
    Points : 16
    Points
    16
    Par défaut Modifier le Control Template Dans une classe DesignerCanvas.cs
    voila mon code DesignerItem.xaml:

    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
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:sys="clr-namespace:System;assembly=mscorlib"
                        xmlns:s="clr-namespace:essayeService"
                        xmlns:c="clr-namespace:essayeService.Controls">
     
        <!-- Connector Style -->
        <!-- les Connector son les points qui nous permet des tracer les lignes-->
        <Style x:Name="styleCon"  TargetType="{x:Type s:Connector}">
            <Setter Property="Width" Value="8"/>
            <Setter Property="Height" Value="8"/>
            <Setter Property="Cursor" Value="Cross"/>
            <Setter Property="SnapsToDevicePixels" Value="true"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type s:Connector}">
                        <Grid>
                            <!-- transparent extra space makes connector easier to hit -->
                            <!--c un carrer qui nous permet de dessiner la line entre les object-->
                            <Rectangle Fill="red" Margin="-2"/>
                            <Rectangle Fill="Lavender" StrokeThickness="1" Stroke="#AA000080"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="o"  TargetType="{x:Type s:Connector}">
            <Setter Property="Width" Value="8"/>
            <Setter Property="Height" Value="8"/>
            <Setter Property="Cursor" Value="Cross"/>
            <Setter Property="SnapsToDevicePixels" Value="true"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type s:Connector}">
                        <Grid>
                            <!-- transparent extra space makes connector easier to hit -->
                            <!--c un carrer qui nous permet de dessiner la line entre les object-->
                            <Rectangle Fill="red" Margin="-2"/>
                            <Rectangle Fill="Lavender" StrokeThickness="1" Stroke="#AA000080"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
     
        <!--*************************************************************************************-->
        <!-- c'est le partie suiavnte que je veux modifier dans le code source , dans la classe 
             DesignerCanvas.cs    -->
        <!--************************************************************************************-->
        <!-- ConnectorDecoratorTemplate Default Template -->
        <ControlTemplate x:Key="ConnectorDecoratorTemplate" TargetType="{x:Type Control}">
     
            <Grid x:Name="PART_LesPointDeConnexion" Margin="3">
     
                <!-- la partie suivante est la partie que je veux la definir dans la classe DesignerCanvas.cs
                  -->
                    <Grid.RowDefinitions>
                        <RowDefinition Height="0.5*"/>
                        <RowDefinition Height="0.5*"/>
                    </Grid.RowDefinitions>
                <s:Connector x:Name="toi" Orientation="Left" VerticalAlignment="Center" HorizontalAlignment="Left" Grid.Row="0"></s:Connector>
                <s:Connector Orientation="Left" VerticalAlignment="Center" HorizontalAlignment="Left" Grid.Row="1"></s:Connector>
     
                </Grid>
     
        </ControlTemplate>
     
        <!-- ResizeDecorator Default Template -->
        <ControlTemplate x:Key="ResizeDecoratorTemplate" TargetType="{x:Type Control}">
            <Grid Opacity="0.7" SnapsToDevicePixels="true">
                <c:ResizeThumb Height="3" Cursor="SizeNS" Margin="0 -4 0 0"
                         VerticalAlignment="Top" HorizontalAlignment="Stretch"/>
                <c:ResizeThumb Width="3" Cursor="SizeWE" Margin="-4 0 0 0"
                         VerticalAlignment="Stretch" HorizontalAlignment="Left"/>
                <c:ResizeThumb Width="3" Cursor="SizeWE" Margin="0 0 -4 0"
                         VerticalAlignment="Stretch" HorizontalAlignment="Right"/>
                <c:ResizeThumb Height="3" Cursor="SizeNS" Margin="0 0 0 -4"
                         VerticalAlignment="Bottom" HorizontalAlignment="Stretch"/>
                <c:ResizeThumb Width="7" Height="7" Cursor="SizeNWSE" Margin="-6 -6 0 0"
                         VerticalAlignment="Top" HorizontalAlignment="Left"/>
                <c:ResizeThumb Width="7" Height="7" Cursor="SizeNESW" Margin="0 -6 -6 0"
                         VerticalAlignment="Top" HorizontalAlignment="Right"/>
                <c:ResizeThumb Width="7" Height="7" Cursor="SizeNESW" Margin="-6 0 0 -6"
                         VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
                <c:ResizeThumb Width="7" Height="7" Cursor="SizeNWSE" Margin="0 0 -6 -6"
                         VerticalAlignment="Bottom" HorizontalAlignment="Right"/>
            </Grid>
        </ControlTemplate>
     
        <!-- DragThumb Default Template -->
        <Style TargetType="{x:Type c:DragThumb}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type c:DragThumb}">
                        <Rectangle Fill="Transparent"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
     
        <!--***********************************************************************************-->
        <!-- c'est dans la partie suivante ou on appelle le controle template pour le Connector      -->
     
        <!--***********************************************************************************-->
        <!-- DesignerItem Style -->
        <Style  x:Key="DesignStyle" TargetType="{x:Type s:DesignerItem}">
            <Setter Property="MinWidth" Value="10"/>
            <Setter Property="MinHeight" Value="10"/>
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type s:DesignerItem}">
                        <Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}"
                              >
                            <!-- PART_DragThumb -->
                            <c:DragThumb x:Name="PART_DragThumb" 
                                         Cursor="SizeAll"/>
                            <!-- PART_ResizeDecorator -->
                            <Control x:Name="PART_ResizeDecorator" 
                                     Visibility="Collapsed"
                                     Template="{StaticResource ResizeDecoratorTemplate}"/>
                            <!-- PART_ContentPresenter -->
                            <ContentPresenter x:Name="PART_ContentPresenter"
                                              HorizontalAlignment="Stretch"
                                              VerticalAlignment="Stretch"
                                              Content="{TemplateBinding ContentControl.Content}"
                                              Margin="{TemplateBinding ContentControl.Padding}"/>
                            <!-- PART_ConnectorDecorator -->
                            <Control x:Name="PART_ConnectorDecorator"
                                     Visibility="Hidden"
                                     Template="{StaticResource ConnectorDecoratorTemplate}"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <DataTrigger Value="True" Binding="{Binding RelativeSource={RelativeSource Self},Path=IsGroup}">
                                <Setter TargetName="PART_DragThumb" Property="Visibility" Value="Collapsed"/>
                            </DataTrigger>
                            <MultiDataTrigger>
                                <MultiDataTrigger.Conditions>
                                    <Condition Value="True" Binding="{Binding RelativeSource={RelativeSource Self},Path=IsSelected}"/>
                                    <Condition Value="{x:Static sys:Guid.Empty}" Binding="{Binding RelativeSource={RelativeSource Self},Path=ParentID}"/>
                                </MultiDataTrigger.Conditions>
                                <Setter TargetName="PART_ResizeDecorator" Property="Visibility" Value="Visible"/>
                            </MultiDataTrigger>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Setter TargetName="PART_ConnectorDecorator" Property="Visibility" Value="Visible"/>
                            </Trigger>
                            <DataTrigger Value="True" Binding="{Binding RelativeSource={RelativeSource Self},Path=IsDragConnectionOver}">
                                <Setter TargetName="PART_ConnectorDecorator" Property="Visibility" Value="Visible"/>
                            </DataTrigger>
                            <DataTrigger Value="True" Binding="{Binding RelativeSource={RelativeSource Self},Path=IsGroup}">
                                <Setter TargetName="PART_ConnectorDecorator" Property="Visibility" Value="Hidden"/>
                            </DataTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ResourceDictionary>

    code source pour la classe:DesignerCanvas.cs

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.IO;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Markup;
    using System.Xml;
    using System.Windows.Media;
    using System.Windows.Shapes;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
     
    namespace essayeService
    {
        public partial class DesignerCanvas : Canvas
        {
            private Point? rubberbandSelectionStartPoint = null;
     
            private SelectionService selectionService;
            internal SelectionService SelectionService
            {
                get
                {
                    if (selectionService == null)
                        selectionService = new SelectionService(this);
     
                    return selectionService;
                }
            }
     
            protected override void OnMouseDown(MouseButtonEventArgs e)
            {
                base.OnMouseDown(e);
                if (e.Source == this)
                {
                    // in case that this click is the start of a 
                    // drag operation we cache the start point
     
                    // sa c pour la selection dans la canvas"" dans le vide du canvas ""
                    this.rubberbandSelectionStartPoint = new Point?(e.GetPosition(this));
     
                    // if you click directly on the canvas all 
                    // selected items are 'de-selected'
                    SelectionService.ClearSelection();
                    Focus();
                    e.Handled = true;
                }
            }
     
            /******************************************************/
            /* methode pour pouvoir selectionner dans le vide ****/
            /****************************************************/
            protected override void OnMouseMove(MouseEventArgs e)
            {
                base.OnMouseMove(e);
     
                // if mouse button is not pressed we have no drag operation, ...
                if (e.LeftButton != MouseButtonState.Pressed)
                    this.rubberbandSelectionStartPoint = null;
     
                // ... but if mouse button is pressed and start
                // point value is set we do have one
                if (this.rubberbandSelectionStartPoint.HasValue)
                {
                    // create rubberband adorner
                    AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(this);
                    if (adornerLayer != null)
                    {
                        RubberbandAdorner adorner = new RubberbandAdorner(this, rubberbandSelectionStartPoint);
                        if (adorner != null)
                        {
                            adornerLayer.Add(adorner);
                        }
                    }
                }
                e.Handled = true;
            }
     
     
            /***********************************************************************************************************************/
            /***** c'est dans cette methode que je veux modifier mon controle template pour lui rajouter des connecteur ***********/
            /*********************************************************************************************************************/
     
            protected override void OnDrop(DragEventArgs e)
            {
                /***************************************************************************************************************/
                /* ça c'est que je fait maintenant mais sans modifier le controle template pour le connector qui est definie dans 
                 * DesigneItem.xaml,
                /*****************************************************************************************************************/
     
                Grid ss = new Grid();
                ss.RowDefinitions.Add(new RowDefinition { Height = new GridLength(0.5, GridUnitType.Star) });
                ss.RowDefinitions.Add(new RowDefinition { Height = new GridLength(0.5, GridUnitType.Star) });
     
                TextBlock v = new TextBlock();
                v.Text = "Test";
                Grid.SetRow(v,1);
                ss.Children.Add(v);
     
                v.VerticalAlignment = VerticalAlignment.Center;
     
                DesignerItem newItem = null;
                newItem = new DesignerItem();
                newItem.Height = 100;
                newItem.Width = 100;
                newItem.SetResourceReference(StyleProperty, "DesignStyle");
     
     
                ss.Background = Brushes.Gray;
                ss.IsHitTestVisible = false;
                newItem.Content = ss;
     
                SetConnectorDecoratorTemplate(newItem);
                Canvas.SetLeft(newItem,50);
                Canvas.SetTop(newItem, 50);
                this.Children.Add(newItem);
     
     
                /*************************************************************************************************************************/
                /*ici c'est le code que j'ai essayé pour modifier le controle template mais sa ne fonctionne pas car lorsque je cherche 
                 * la Grid pour la modifier en ajoutant des Conntector, sa donnr une exception 
                 /*****************************************************************************************************************/
     
                /*
                DesignerItem newItem = null;
                newItem = new DesignerItem();
     
                newItem.SetResourceReference(StyleProperty, "DesignStyle");
               
                Grid w = newItem.Template.FindName("PART_LesPointDeConnexion", newItem) as Grid; // ici le systeme bloque et je recois null dans la grid w 
                MessageBox.Show("" + w);
     
                w.RowDefinitions.Add(new RowDefinition { Height = new GridLength(0.5, GridUnitType.Star) });
                w.RowDefinitions.Add(new RowDefinition { Height = new GridLength(0.5, GridUnitType.Star) });
                Connector cn = new Connector();
                cn.Style = this.FindResource("styleCon") as Style;
                cn.VerticalAlignment = VerticalAlignment.Bottom;
                cn.HorizontalAlignment = HorizontalAlignment.Left;
                w.Children.Add(cn);
                Grid.SetColumn(cn, 0);
                Grid.SetRow(cn, 1);
                
                 ss.Background = Brushes.Green;
                ss.IsHitTestVisible = false;
                newItem.Content = ss;
     
                SetConnectorDecoratorTemplate(newItem);
                Canvas.SetLeft(newItem,50);
                Canvas.SetTop(newItem, 50);
                this.Children.Add(newItem);
                 
                 */
     
            }
     
            protected override Size MeasureOverride(Size constraint)
            {
     
                Size size = new Size();
     
                foreach (UIElement element in this.InternalChildren)
                {
                    double left = Canvas.GetLeft(element);
                    double top = Canvas.GetTop(element);
                    left = double.IsNaN(left) ? 0 : left;
                    top = double.IsNaN(top) ? 0 : top;
     
                    //measure desired size for each child
                    element.Measure(constraint);
     
                    Size desiredSize = element.DesiredSize;
                    if (!double.IsNaN(desiredSize.Width) && !double.IsNaN(desiredSize.Height))
                    {
                        size.Width = Math.Max(size.Width, left + desiredSize.Width);
                        size.Height = Math.Max(size.Height, top + desiredSize.Height);
                    }
                }
                // add margin 
                size.Width += 10;
                size.Height += 10;
     
                return size;
            }
     
            private void SetConnectorDecoratorTemplate(DesignerItem item)
            {
     
     
                if (item.ApplyTemplate() && item.Content is UIElement)
                {
     
                    ControlTemplate template = DesignerItem.GetConnectorDecoratorTemplate(item.Content as UIElement);
                    Control decorator = item.Template.FindName("PART_ConnectorDecorator", item) as Control;
                    if (decorator != null && template != null)
                        decorator.Template = template;
     
                }
     
            }
     
        }
    }
    MainWindow.xaml

    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
    <Window x:Class="essayeService.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:s="clr-namespace:essayeService"
            xmlns:c="clr-namespace:essayeService.Controls"
            Title="MainWindow" Height="500" Width="500">
     
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="369*"/>
                <ColumnDefinition Width="148*"/>
            </Grid.ColumnDefinitions>
            <TreeView Grid.Column="1" Margin="2,0,0,0">
                <TreeViewItem x:Name="moi2"  Header="List Component">
                    <TreeViewItem >
                        <TreeViewItem.Header>
                            <StackPanel Orientation="Horizontal" MouseLeftButtonDown="TreeViewItem_MouseLeftButtonDown">
     
                            <TextBlock Text="Component 1"></TextBlock>
                        </StackPanel>
                        </TreeViewItem.Header>
                    </TreeViewItem>
                    <TreeViewItem>
                        <TreeViewItem.Header>
                            <StackPanel Orientation="Horizontal" MouseLeftButtonDown="TreeViewItem_MouseLeftButtonDown">
     
                                <TextBlock Text="Component2"></TextBlock>
                            </StackPanel>
                        </TreeViewItem.Header>
                    </TreeViewItem>
                </TreeViewItem>
            </TreeView>
            <GridSplitter Width="5" Focusable="False" VerticalAlignment="Stretch" Background="Red" HorizontalAlignment="Right"/>
                <Grid Margin="2">
                <TextBlock>Drag an element from "List Component" and Drop it here!</TextBlock>
                <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Grid.Column="0">
     
                    <s:DesignerCanvas Focusable="true" x:Name="MyDesigner" 
                                Background="Beige" 
                                Margin="18" FocusVisualStyle="{x:Null}">
                     </s:DesignerCanvas>
     
                </ScrollViewer>
     
            </Grid>
            </Grid>
     
    </Window>

    Comment je dois faire pour pouvoir modifier le Control Template dans le methode OnDrop dans DesignerCanvas.cs

  5. #5
    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
    Re

    1/Quand tu crees une instance de ton control DesignerItem => newItem ,il faut lui affecter ton ControlTemplate ou ton Style au chois ...
    2/on utilise dans les 2 cas la methode DesignerItem.Template.FindName
    3/Cas du ControlTemplate :
    -operation à faire dans l'event Drop du panel (stackpanel ou canvas)..
    -l'affectation d'un Template suffit pour le charger.....!!!
    2/Cas d'utilisation du Style
    - operation à faire dans l'event Initialized de ton control DesignerItem car son Template n'est charge qu'une fois ton control DesignerItem.....initialise...!!!

    Exemple avec template
    code xaml winform:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
     
    <Window x:Class="WpfControlTemplateByCode.Window1"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfControlTemplateByCode" 
            Title="Window1" Height="300" Width="300">
        <StackPanel 
            x:Name="pnl"
            Margin="15"
            Background="LightGray"  
            PreviewMouseDown="pnl_PreviewMouseDown">
     
        </StackPanel >
     
     
    </Window>
    code behind .cs 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
    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
     
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
     
    namespace WpfControlTemplateByCode
    {
        /// <summary>
        /// Logique d'interaction pour Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
            MyControl ctl = null;
            //TON CONTROLTEMPLATE
            ControlTemplate myTemplate=null;
            public Window1()
            {
                InitializeComponent();
     
            }
           int indexRow;
           private void pnl_PreviewMouseDown(object sender, MouseButtonEventArgs e)
            {
     
     
                RowDefinition rowdef;
                Connector cn;
                ctl = new MyControl();
                //AFFECTE LE CONTROLTEMPLATE
                myTemplate = this.FindResource("ConnectorDecoratorTemplate") as ControlTemplate;
                ctl.Template = myTemplate;
                this.pnl.Children.Add(ctl);
     
               //la suite fatidique
                Grid grd = ctl.Template.FindName("PART_LesPointDeConnexion",ctl ) as Grid;
     
     
                rowdef = new RowDefinition();
                rowdef.Height = new GridLength(0.5, GridUnitType.Auto);
                grd.RowDefinitions.Add(rowdef);
                indexRow = grd.RowDefinitions.Count - 1;
     
                cn = new Connector();
                cn.Style = this.FindResource("styleCon") as Style;
                cn.VerticalAlignment = VerticalAlignment.Bottom;
                cn.HorizontalAlignment = HorizontalAlignment.Left;
                grd.Children.Add(cn);
                Grid.SetColumn(cn, 0);
                Grid.SetRow(cn, indexRow);
     
     
                rowdef = new RowDefinition();
                rowdef.Height = new GridLength(0.5, GridUnitType.Auto);
                grd.RowDefinitions.Add(rowdef);
                indexRow = grd.RowDefinitions.Count - 1;
     
                cn = new Connector();
                cn.Style = this.FindResource("styleCon") as Style;
                cn.VerticalAlignment = VerticalAlignment.Bottom;
                cn.HorizontalAlignment = HorizontalAlignment.Right;
                grd.Children.Add(cn);
                Grid.SetColumn(cn, 1);
                Grid.SetRow(cn, indexRow);
     
            }
     
     
     
     
        }
    }
    Exemple avec Style
    code xaml winform:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    <Window x:Class="WpfControlTemplateByCode.Window2"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfControlTemplateByCode" 
            Title="Window2" Height="300" Width="300">
        <StackPanel 
            x:Name="pnl"
            Margin="15"
            Background="LightGray"  
            PreviewMouseDown="pnl_PreviewMouseDown">
     
        </StackPanel >
    </Window>
    code behind .cs 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
    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
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
     
    namespace WpfControlTemplateByCode
    {
        /// <summary>
        /// Logique d'interaction pour Window2.xaml
        /// </summary>
        public partial class Window2 : Window
        {
            MyControl ctl = null;
            //TON STYLE
            Style myStyle = null;
            public Window2()
            {
                InitializeComponent();
                // AFFECTE LE STYLE
                myStyle = this.FindResource("ConnectorDecoratorStyle") as Style; 
            }
            int indexRow;
            private void pnl_PreviewMouseDown(object sender, MouseButtonEventArgs e)
            {
     
                ctl = new MyControl();
                //AFFECTE LE STYLE
                ctl.Style = myStyle;
                this.pnl.Children.Add(ctl);
                ctl.Initialized += new EventHandler(ctl_Initialized);
               }
     
     
            void ctl_Initialized(object sender, EventArgs e)
            {
                RowDefinition rowdef;
                Connector cn;
                //la suite fatidique
                Grid grd = ctl.Template.FindName("PART_LesPointDeConnexion", ctl) as Grid;
                rowdef = new RowDefinition();
                rowdef.Height = new GridLength(0.5, GridUnitType.Auto);
                grd.RowDefinitions.Add(rowdef);
                indexRow = grd.RowDefinitions.Count - 1;
     
                cn = new Connector();
                cn.Style = this.FindResource("styleCon") as Style;
                cn.VerticalAlignment = VerticalAlignment.Bottom;
                cn.HorizontalAlignment = HorizontalAlignment.Left;
                grd.Children.Add(cn);
                Grid.SetColumn(cn, 0);
                Grid.SetRow(cn, indexRow);
     
     
                rowdef = new RowDefinition();
                rowdef.Height = new GridLength(0.5, GridUnitType.Auto);
                grd.RowDefinitions.Add(rowdef);
                indexRow = grd.RowDefinitions.Count - 1;
     
                cn = new Connector();
                cn.Style = this.FindResource("styleCon") as Style;
                cn.VerticalAlignment = VerticalAlignment.Bottom;
                cn.HorizontalAlignment = HorizontalAlignment.Right;
                grd.Children.Add(cn);
                Grid.SetColumn(cn, 1);
                Grid.SetRow(cn, indexRow);
     
            }
     
     
        }
    }
    bon code...

  6. #6
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2014
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Algérie

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Enseignement

    Informations forums :
    Inscription : Janvier 2014
    Messages : 15
    Points : 16
    Points
    16
    Par défaut Re
    Merci Infiniment monsieur Mabrouki ,c'est exactement ce que je cherchais, WLH je ne sais pas comment vous remercié!!!! ...

  7. #7
    Nouveau Candidat au Club
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2016
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 63
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2016
    Messages : 1
    Points : 1
    Points
    1
    Par défaut Designer
    Merci Infiniment de poster le code de cet exemple

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

Discussions similaires

  1. Réponses: 4
    Dernier message: 30/06/2011, 13h12
  2. WPF ListBox : comment itérer dans les ListBoxItem dans le "code behind"
    Par jmnicolas dans le forum Windows Presentation Foundation
    Réponses: 2
    Dernier message: 07/10/2010, 15h24
  3. Réponses: 1
    Dernier message: 20/08/2009, 12h12
  4. Réponses: 1
    Dernier message: 06/11/2008, 13h02
  5. Réponses: 1
    Dernier message: 20/01/2007, 11h47

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