在其他对象

时间:2017-09-20 12:19:27

标签: c# wpf properties observable

假设我有以下课程(型号)

public class Employee : ObservableBase {
  private int _id;
  public int Id {
    get { return _id; }
    set { this.Update( x => x.Id, ( ) => _id = value, _id, value ); }
  }

  private string _name;
  public string Name {
    get { return _name; }
    set { this.Update( x => x.Name, ( ) => _name = value, _name, value ); }
  }

  private EmployeeStatus _level;
  public EmployeeStatus Level {
    get { return _level; }
    set { this.Update( x => x.Level, ( ) => _level = value, _level, value ); }
  }

  private RecordState _state;
  public RecordState State {
    get { return _state; }
    set { this.Update( x => x.State, ( ) => _state = value, _state, value ); }
  }

}

public class Enums {
  public enum EmployeeStatus {
    Junior = 1,
    Medior = 2,
    Senior = 3
  }

  public enum RecordState {
    Add = 1,
    Edit = 2,
    Delete = 3
  }
}

我在它周围写了一个包,以便能够公开额外的属性(确定可见性并在某些控件上禁用/启用我的View):

public class EmployeeCustom : ObservableBase {

  private Employee _employee;
  public Employee Employee {
    get { return _employee; }
    set { this.Update( x => x.Employee, ( ) => _employee = value, _employee, value ); }
  }

  public Visibility SeniorTestVisible {
    get { return Employee.Level == EmployeeStatus.Senior && Employee.State == RecordState.Add ? Visibility.Visible : Visibility.Collapsed; }
  }


}

我的 EmployeeCustom 类在我的View as DataContext中使用 如何确定级别的更改时间,以便我的SeniorTestVisible可以"刷新"如果这些属性中的任何一个在Employee对象中发生更改。请注意我不允许对员工类进行任何更改。仅限于EmployeeCustom。

1 个答案:

答案 0 :(得分:0)

  

如何确定StateLevel的更改时间,以便SeniorTestVisible可以在Employee对象中的任何属性更改时“刷新”。

为任何这些属性发生更改时Employee类(希望)引发的事件挂钩事件处理程序,并为PropertyChanged属性提升SeniorTestVisible事件每当发生这种情况时EmployeeCustom类,例如:

public class EmployeeCustom : ObservableBase
{
    private Employee _employee;
    public Employee Employee
    {
        get { return _employee; }
        set
        {
            if (_employee != null)
                _employee.PropertyChanged -= OnEmployeePropertyChanged;
            if(value != null)
                value..PropertyChanged += OnEmployeePropertyChanged;

            this.Update(x => x.Employee, () => _employee = value, _employee, value);
        }
    }

    public Visibility SeniorTestVisible
    {
        get { return Employee.Level == EmployeeStatus.Senior && Employee.State == RecordState.Add ? Visibility.Visible : Visibility.Collapsed; }
    }

    public void OnEmployeePropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if(e.PropertyName == "Level" || e.PropertyName == "State")
        {
            this.NotifyPropertyChanged("SeniorTestVisible");
        }
    }
}

如果Employee课程没有引发任何事件,你就无法知道。