2016-10-12 37 views
0

我需要帮助在我自己的数据结构类中实现INotifyPropertyChanged。这是为了一个类的分配,但是实现INotifyPropertyChanged是我在上面做的,超出了规定的要求。如何实现INotifyPropertyChanged

我有一个名为'BusinessRules'的类,它使用SortedDictionary来存储'Employee'类型的对象。我有一个DataGridView显示我所有的员工,我想用我的BusinessRules类对象作为我的DataGridView的数据源。 BusinessRules容器是分配所必需的。我试图在这个类中实现INotifyPropertyChanged,但没有成功。

我工作的DataSource是一个BindingList。目前,我正在使用该BindingList作为'sidecar'容器并将其设置为我的DataSource。我对BusinessRules类对象所做的每个更改都镜像到了我的BindingList类对象。但是这显然是拙劣的编程,我想做得更好。

我试图在BusinessRules中实现INotifyPropertyChanged,但是当我将实例化的BusinessRules对象设置为DataSource时,DataGridView不显示任何内容。我怀疑问题是使用NotifyPropertyChanged()方法。我不知道该怎么传递给它,也不知道如何处理传入的内容。大多数示例处理更改名称,但是我更关心何时将新对象添加到SortedDictionary中。

private void NotifyPropertyChanged(Employee emp) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(emp.FirstName)); 
    } 

需要更改哪些内容才能使其正常工作?你会解释为什么我的尝试不起作用吗?

我在StackOverflow上形成我的问题是个臭名昭着的错误。这不是故意的。请让我知道您需要的其他信息,我会尽快提供。

Here is a link to my BusinessRules source code

回答

2

如果您阅读how to implement MVVM上的教程将会非常有帮助。

你想有一个基类实现INotifyPropertyChanged接口。所以你所有的视图模型都应该从这个基类继承。

public class ViewModelBase : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    protected void RaisePropertyChangedEvent(string propertyName) 
    { 
     var handler = PropertyChanged; 
     if (handler != null) 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

// This sample class DelegateCommand is used if you wanna bind an event action with your view model 
public class DelegateCommand : ICommand 
{ 
    private readonly Action _action; 

    public DelegateCommand(Action action) 
    { 
     _action = action; 
    } 

    public void Execute(object parameter) 
    { 
     _action(); 
    } 

    public bool CanExecute(object parameter) 
    { 
     return true; 
    } 

#pragma warning disable 67 
    public event EventHandler CanExecuteChanged; 
#pragma warning restore 67 
} 

您的视图模型应该看起来像这样。

public sealed class BusinessRules : ViewModelBase 

下面是如何利用RaisePropertyChangedEvent的示例。

public sealed class Foo : ViewModelBase 
{ 
    private Employee employee = new Employee(); 

    private string Name 
    { 
     get { return employee.Name; } 
     set 
     { 
      employee.Name = value; 
      RaisePropertyChangedEvent("Name"); 
      // This will let the View know that the Name property has updated 
     } 
    } 

    // Add more properties 

    // Bind the button Command event to NewName 
    public ICommand NewName 
    { 
     get { return new DelegateCommand(ChangeName)} 
    } 

    private void ChangeName() 
    { 
     // do something 
     this.Name = "NEW NAME"; 
     // The view will automatically update since the Name setter raises the property changed event 
    } 
} 

我真的不知道你想做的事,所以我会离开我的例子是这样的。更好地阅读不同的教程,学习曲线有点陡峭。

相关问题