将IsChecked绑定到位字段

huangapple go评论93阅读模式
英文:

Bind IsChecked to bitfield

问题

我有一个类似这样的位字段:

[Flags]
public enum EmployeeType
{
    None = 0,
    IsInOffice = 1,
    IsManager = 2,
    IsOnVacation = 4,
    ...
}

我的用户界面有一个员工列表框,我想要实现复选框来过滤列表。这个列表框绑定到一个过滤属性,如下所示:

public IEnumerable<Employee> FilteredEmployees
    => _employees.Where(e => _regexFilter.IsMatch(e.FullName)
                            && (!EmployeeType.HasFlag(EmployeeType.IsInOffice) || e.IsLoggedIn)
                            && (!EmployeeType.HasFlag(EmployeeType.IsManager) || e.RoleID >= 4)
                            && (!EmployeeType.HasFlag(EmployeeType.IsOnVacation) || TimeRec.GetStatusID(e.ID) == 7))
                 .OrderBy(e => e.FullName);

我的问题是,我无法从转换器中获得正确的返回值,因为那里不知道所有标志的当前状态,而且我也无法将所有标志的当前状态传递到转换器中。

我能够激活一个标志,但无法在不激活或激活其他标志的情况下取消激活任何标志,这将是意外的行为。

英文:

I have a bitfield like this:

[Flags]
public enum EmployeeType
{
    None = 0,
    IsInOffice = 1,
    IsManager = 2,
    IsOnVacation = 4,
    ...
}

My UI has a listbox of all employees and I want to implement checkboxes to filter the list. This listbox is bound to a filter property like this:

public IEnumerable&lt;Employee&gt; FilteredEmployees
    =&gt; _employees.Where(e =&gt; _regexFilter.IsMatch(e.FullName)
                                &amp;&amp; (!EmployeeType.HasFlag(EmployeeType.IsInOffice) || e.IsLoggedIn)
                                &amp;&amp; (!EmployeeType.HasFlag(EmployeeType.IsManager) || e.RoleID &gt;= 4)
                                &amp;&amp; (!EmployeeType.HasFlag(EmployeeType.IsOnVacation) || TimeRec.GetStatusID(e.ID) == 7))
                 .OrderBy(e =&gt; e.FullName);

My problem now is that I can't get a correct return value from the converter, since the current state of all flags is not known there and I also can't manage to get the current state of all flags into the converter.

I'm able to activate a flag but I'm unable to deactivate any flag without deactivating or activating others, which would be unintended behavior.

答案1

得分: 1

似乎我使用这个得到了它:

转换器:

if ((bool)value)
    return (EmployeeType)parameter;
else
    return ~(EmployeeType)parameter;

设置器:

if ((int)value &gt; 0)
    _employeeType |= value;
else
    _employeeType &amp;= value;

不确定它是否只是在我的情况下有效的一个技巧,但是嗯,它有效:D

英文:

Seems like I got it using this:

Converter:

if ((bool)value)
    return (EmployeeType)parameter;
else
    return ~(EmployeeType)parameter;

Setter:

if ((int)value &gt; 0)
    _employeeType |= value;
else
    _employeeType &amp;= value;

Not 100% sure if it's a hack that just works in my scenario but well, it works 将IsChecked绑定到位字段

huangapple
  • 本文由 发表于 2023年8月10日 17:03:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76874194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定