Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to get the type of datacontext of a listbox at runtime in wpf?
Posted

1 solution

You can use the GetType method to find the Type of any entity. You need to be careful when trying to find the Type from a DataContext though, because unless the DataContext for the ListBox is specifically set, it will return the ViewModel or Window as the Type. For Example, if I have these classes:-

C#
public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    public class People : ObservableCollection<Person>
    {
        public People()
        {
            for (int i = 0; i < 5; i++)
            {
                Person person = new Person() { Age = i + 20, Name = "Person " + i.ToString() };
                this.Add(person);
            }
        }
    }


and I have a Property in my code behind like so:-

C#
public People peoples;
        public People Peoples
        {
            get
            {
                return peoples;
            }
            set
            {
                peoples = value;
                NotifyPropertyChanged("Peoples");
            }
        }


which I set as the ItemsSource of my ListBox

Type contextType = lb.DataContext.GetType();


gives me MainWindow(the name of my window)

Type contextType = lb.ItemsSource.GetType();


gives me People as the Type and

Type contextType = lb.Items[0].GetType();

gives me Person as the Type.
 
Share this answer
 
Comments
[no name] 28-Nov-11 1:22am    
my vote of 5.
Wayne Gaylard 28-Nov-11 1:35am    
Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900