如何在WPF中在运行时获取列表框的数据上下文类型 [英] how to get the type of datacontext of a listbox at runtime in wpf

查看:561
本文介绍了如何在WPF中在运行时获取列表框的数据上下文类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在wpf中在运行时获取列表框的数据上下文类型?

how to get the type of datacontext of a listbox at runtime in wpf?

推荐答案

您可以使用GetType方法查找任何实体的类型.但是,在尝试从DataContext查找类型时需要小心,因为除非专门设置ListBox的DataContext,否则它将返回ViewModel或Window作为Type.例如,如果我有以下课程:-

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:-

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:-

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



我将其设置为ListBox的ItemsSource



which I set as the ItemsSource of my ListBox

Type contextType = lb.DataContext.GetType();



给我MainWindow(窗口的名称)



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();


给我Person作为类型.


gives me Person as the Type.


这篇关于如何在WPF中在运行时获取列表框的数据上下文类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆