Yeah I got my answer...
chkListBoxPerson.ItemsSource = typeof(Person).GetProperties();
chkListBoxPerson.DisplayMemberPath = "Name";
Here chkListBoxPerson is the name of my CheckListBox.
문제
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.
해결책 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.