How can I make a boolean property like a RadioButton? You know, like a RadioButton, only one can be selected?
Like example below.
When I set one Employee IsResponsiblePerson
to true, it should set all others to false. Without using a loop.
var list = new ObservableCollection<Employee>();
public class Employee
{
public string Name{get;set;}
public string Surname{get;set;}
public bool IsResponsiblePerson{get;set;}
}
What i'd probably do if I didn`t want to use loops, is, as Lasse V. Karlsen says in a comment, store instead the name of the "ResponsiblePerson" in another property:
static string ResponsiblePerson {get;set;}
And change the IsResponsiblePerson
property to something like this:
public bool IsResponsiblePerson
{
get
{
return this.Name == ResponsiblePerson;
}
set
{
if (value)
{
ResponsiblePerson = this.Name;
}
else
{
if (this.Name == ResponsiblePerson)
{
ResponsiblePerson = "";
}
}
}
}
Sample code:
List<Employee> employees = new List<Employee>() { new Employee() { Name = "name1" },
new Employee() { Name = "name2" },
new Employee() { Name = "name3" } };
Employee emp1 = employees.Where(x => x.Name == "name1").First();
emp1.IsResponsiblePerson = true;
Employee emp2 = employees.Where(x => x.Name == "name2").First();
emp2.IsResponsiblePerson = true;
foreach (Employee e in employees)
{
Console.WriteLine(e.IsResponsiblePerson); //false true false
}
I've made a DotNetFiddle sample here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With