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 :

ItemContainerGenerator retourne null


Sujet :

C#

  1. #1
    Membre régulier
    Inscrit en
    Juin 2009
    Messages
    106
    Détails du profil
    Informations forums :
    Inscription : Juin 2009
    Messages : 106
    Points : 85
    Points
    85
    Par défaut ItemContainerGenerator retourne null
    Bonsoir, j'ai trois ComboBox, et un DataGrid, les deux premier ComboBox me sert à filtrer le contenue qui est sur le troisième ComboBox. Tous ces contrôleurs ont un bind respectivement sur des Observablecollection.

    D'une autre manière, je veux que quand l'utilisateur choisie un item du premier ou du deuxième ComboBox, selon son choix, je cache les items non concernés du troisièmement ComboBox et du DataGrid.

    Voici le code XAML pour un ComboBox.
    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
    <ComboBox Name="monCB_1"....>
                                <ComboBox.ItemsSource>
                                    <CompositeCollection>
                                        <TextBlock Text="{DynamicResource All}" />
                                        <CollectionContainer x:Name="maCC_1"/>
                                    </CompositeCollection>
                                </ComboBox.ItemsSource>
    </ComboBox>
     
    <ComboBox Name="monCB_2"....>
                                <ComboBox.ItemsSource>
                                    <CompositeCollection>
                                        <TextBlock Text="{DynamicResource All}" />
                                        <CollectionContainer x:Name="maCC_2"/>
                                    </CompositeCollection>
                                </ComboBox.ItemsSource>
    </ComboBox>
     
    <ComboBox Name="monCB_3" DisplayMemberPath="Nom" SelectedValue="Id"....>
                                <ComboBox.ItemsSource>
                                    <CompositeCollection>
                                        <TextBlock Text="{DynamicResource All}" />
                                        <CollectionContainer x:Name="maCC_3"/>
                                    </CompositeCollection>
                                </ComboBox.ItemsSource>
    </ComboBox>
    Le Bind:
    maCC_#.Collection = maListe_#; #: 1,2,3

    * Lors de l'affichage il n'y a aucun problème.

    Voici ce que j'ai mis dans l’événement monCB_1_SelectionChanged:
    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
    monCB1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
       foreach(maClass c in maList) // ou monCB.Items ou maCC.Collection
        {
             if() // Traitmeent du cas de "All" 
             {
     
               ((DataGridRow)MonDG.ItemContainerGenerator.ContainerFromIndex(VehicleTrackingDataDic[v.Id].DataGridIndex)).Visibility = Visibility.Visible;
               ((ComboboxItem)monCB_3.ItemContainerGenerator.ItemContainerGenerator.ContainerFromItem(c)).Visibility = Visibility.Visible;
             }
             else
             {
                if() // J'ai une condition qui doit être vérifie
                   {
                     ((DataGridRow)MonDG.ItemContainerGenerator.ContainerFromIndex(VehicleTrackingDataDic[v.Id].DataGridIndex)).Visibility = Visibility.Collapsed;
                     ((ComboboxItem)monCB_3.ItemContainerGenerator.ItemContainerGenerator.ContainerFromItem(c)).Visibility = Visibility.Collapsed;
                   }
                else
                 {
                     ((DataGridRow)MonDG.ItemContainerGenerator.ContainerFromIndex(VehicleTrackingDataDic[v.Id].DataGridIndex)).Visibility = Visibility.Visible;
                     ((ComboboxItem)monCB_3.ItemContainerGenerator.ItemContainerGenerator.ContainerFromItem(c)).Visibility = Visibility.Visible;
                 }
             }
        }
    }
    Sur le DataGrid j'ai aucun problème mais avec mon monCB_3 j'ai l'exception NullReferenceException.

    monCB_3.ItemContainerGenerator.ItemContainerGenerator.ContainerFromItem(c) me retourne null à chaque fois.

    Et même si j'utilise ....ContainerFromIndex(0) pour tester, j'ai toujours NullReferenceException, sachant que dans le debugger je vois que ItemContainerGenerator contient des items.


    Après avoir passé toute l’après-midi dessus, et testé tout ce que j'ai pu trouver sur le net, comme par exemple mettre le VirtualizingStackPanel.IsVirtualizing="False".... J'ai fini par vous solliciter, espérant que quelqu'un pourra me guider.

    Si vous ne m'avez pas bien compris :

    - J'aimerai savoir dans quel cas ItemContainerGenerator.ContainerFromItem/Index retourne null ?
    - Y-a-t-il un autre moyen d'appliquer un filtre ? Sans utiliser le "Remove".

    Merci pour votre attention et bonne soirée.

  2. #2
    Membre régulier
    Inscrit en
    Juin 2009
    Messages
    106
    Détails du profil
    Informations forums :
    Inscription : Juin 2009
    Messages : 106
    Points : 85
    Points
    85
    Par défaut
    Je tiens à m'excuser pour les erreurs précédentes sur mon message.

  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 441
    Points
    4 441
    Par défaut
    bonjour
    Pour les itemsControls il faut s'assuer que le ItemContainerGenerator.ContainerFromItem(data intancedata) a ete genere avant de recupere son intance....dans l'event StatusChanged du ItemContainerGenerator de ton combo n°3 et de marquer un boolean à true:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     this.combox3.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
    code exemple behind .cs Data :
    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
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel;
    using System.Collections.ObjectModel;
     
    namespace WpfItemContainerGenerationSelChanged
    {
       public  class Person:INotifyPropertyChanged
        {
           public Person(int i,string n)
           {
               ID = i;
               Name = n;
           }
           private int _id;
           public int ID
           {
               get { return _id; }
               set { _id = value; OnPropChanged("ID"); }
           }
     
           private string _name;
           public string Name
           {
               get { return _name; }
               set { _name = value; OnPropChanged("Name"); }
           }
            public event PropertyChangedEventHandler PropertyChanged;
            private void OnPropChanged(string s)
            {
                PropertyChangedEventHandler h = PropertyChanged;
                if (h != null) h(this, new PropertyChangedEventArgs(s));
            }
       }
       public class Persons : ObservableCollection<Person>
       {
           private Person p;
           public Persons()
           {
               for (int i = 1; i < 30; i++)
               {
                   p = new Person(i, "Item" + i.ToString());
                   this.Add(p);
               }
           }
     
       }
    }
    code xaml du form utilisateur avec 2 comboboxes (le 2eme joue le role de ton 3eme combo):

    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
    <Window x:Class="WpfItemContainerGenerationSelChanged.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfItemContainerGenerationSelChanged" 
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <local:Persons x:Key="l"></local:Persons> 
        </Window.Resources>
     
        <StackPanel >
            <ComboBox 
                x:Name="cbo1"
               ItemsSource="{StaticResource l}" 
     
               SelectionChanged="cbo1_SelectionChanged">
                <ComboBox.ItemTemplate>
                    <DataTemplate DataType="{x:Type local:Person}">
                        <StackPanel Orientation="Horizontal" >
                            <TextBlock Margin="+5 " Text="{Binding Path=ID}"/>
                            <TextBlock Margin="+5 " Text="{Binding Path=Name}"/>
                        </StackPanel>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
            <Separator Height="50" Background="Yellow" ></Separator>
            <ComboBox 
                x:Name="cbo2"
               ItemsSource="{StaticResource l}" >
                <ComboBox.ItemTemplate>
                    <DataTemplate DataType="{x:Type local:Person}">
                        <StackPanel Orientation="Horizontal" >
                            <TextBlock Margin="+5 " Text="{Binding Path=ID}"/>
                            <TextBlock Margin="+5 " Text="{Binding Path=Name}"/>
                        </StackPanel>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
        </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
    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 WpfItemContainerGenerationSelChanged
    {
        /// <summary>
        /// Logique d'interaction pour MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                this.cbo2.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
            }
            bool b;
            void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
            {
                b = true;
            }
     
            private void cbo1_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                ComboBox cbo=sender as ComboBox ;
                Person p = (Person)cbo.SelectedItem;
                if (p != null && b)
                {
                    if (p.ID < 10)
                    { 
                        ComboBoxItem cboItem = (ComboBoxItem)this.cbo2.ItemContainerGenerator.ContainerFromItem(p);
                        cboItem.Visibility = Visibility.Collapsed;
                    }
                    else if (p.ID >= 10 &&  p.ID <= 20)
                    {
                        ComboBoxItem cboItem = (ComboBoxItem)this.cbo2.ItemContainerGenerator.ContainerFromItem(p);
                        cboItem.Visibility = Visibility.Hidden ;
                    }
                    else if (p.ID > 20 && p.ID <= 30)
                    {
                        ComboBoxItem cboItem = (ComboBoxItem)this.cbo2.ItemContainerGenerator.ContainerFromItem(p);
                        cboItem.Background=Brushes.DarkBlue ;
                        cboItem.Foreground= Brushes.Red;
                    }
     
                }
            }
     
        }
    }
    bon code.......

  4. #4
    Membre régulier
    Inscrit en
    Juin 2009
    Messages
    106
    Détails du profil
    Informations forums :
    Inscription : Juin 2009
    Messages : 106
    Points : 85
    Points
    85
    Par défaut
    Merci beaucoup, j'avais vue cette solution et j'ai pas aimer mettre un bool pour ItemContainerGenerator_StatusChanged. Je croyais que j'ai pas su manipuler ItemContainerGenerator. J'ai bien compris votre façon de traiter ItemContainerGenerator c'est très claire je te dit merci pour l'effort.

    Je suis dessus par c# cette foie si (Il me fait ce je déteste chez JAVA)



    Merci encore.

    Good Coding

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

Discussions similaires

  1. Findcontrol retourne null
    Par Kiwi_violet dans le forum ASP.NET
    Réponses: 1
    Dernier message: 13/04/2007, 12h21
  2. TTF_OpenFont() retournant NULL
    Par FabaCoeur dans le forum SDL
    Réponses: 4
    Dernier message: 11/04/2007, 16h30
  3. GetDC retourne NULL Oo
    Par Groove dans le forum OpenGL
    Réponses: 3
    Dernier message: 02/03/2007, 17h46
  4. Réponses: 3
    Dernier message: 02/03/2007, 11h41
  5. opérateur + dans SELECT retourne null ?
    Par david_chardonnet dans le forum MS SQL Server
    Réponses: 2
    Dernier message: 19/01/2007, 10h47

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