문제

I am using WPF checkListBox And I want to populate its elements with all properties of the class given below. And I have a class named Person

namespace MyProject
{
    public class Person
    {
        public enum PersonFields
        {
            PersonPermission1,
            PersonPermission2,
        }

        bool _personPermission1;
        bool _personPermission2;

        public bool PersonPermission1
        {
            get
            { 
                return _personPermission1; 
            }
            set
            {
                if (_personPermission1!= value)
                {
                    _personPermission1= value;
                }
            }
        }

        public bool PersonPermission2
        {
            get
            {
                return _personPermission1; 
            }
            set
            {
                if (_personPermission2!= value)
                {
                    _personPermission2= value;
                }
            }
        }
    }
}

I want to populate a checkListBox with its Properties dynamically. as in given image. CheckListBox with dynamic properties

도움이 되었습니까?

해결책 2

Yeah I got my answer...

chkListBoxPerson.ItemsSource = typeof(Person).GetProperties();
chkListBoxPerson.DisplayMemberPath = "Name";

Here chkListBoxPerson is the name of my CheckListBox.

다른 팁

I you really want to get the names of all your properties, you can get a list of them like this:

typeof(Person).GetTypeInfo().DeclaredProperties.Select(prop => prop.Name).ToList(),

I noticed you also have a matching inner enum, so you could use its values instead:

Enum.GetNames(typeof(Person.PersonFields));

In both cases you'll still need additional code to set property values based on user actions.

I think a better approach would be to have a Dictionary of permissions:

var personPermissions = new Dictionary<Person.PersonFields, bool>
{
    { Person.PersonFields.PersonPermission1, false },
    { Person.PersonFields.PersonPermission2, false }
}

Now you could bind the Dictionary to ItemsSource, display Key and bind Value to checkbox.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top