我有一个绑定到ObservableCollection<MyEntity>
类型列表的WPF对话框。在对话框中,我希望仅在对ObservableCollection<MyEntity>
列表进行更改时才启用“确定”按钮-包括添加/删除列表中的项目以及修改列表中的各个项目。
为了从列表中添加/删除项目,这很容易-我为CollectionChanged
事件实现了一个处理程序。
我不知道该怎么做,是当单个项目被修改时。说,MyEntity.Name =“ New Value”,MyEntity类需要实现什么接口才能使其“可观察”?
最佳答案
我喜欢slugster提供的答案,这是slugster答案的替代选择。
如果使用DelegateCommnd绑定到“确定”按钮,则可以为CollectionChanged和PropertyChanged添加事件处理程序,以更改简单的布尔标志来控制“确定”按钮的状态。
public class MainViewModel : ViewModelBase
{
public DelegateCommand<object> RunCommand { get; set; }
public DelegateCommand<object> OkCommand { get; set; }
private bool enableOk = false;
private bool setOK = false;
private ObservableCollection<MyEntity> _entites = new ObservableCollection<MyEntity>();
public MainViewModel()
{
_entites.CollectionChanged += (s, e) =>
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
// handle property changing
foreach (MyEntity item in e.NewItems)
{
((INotifyPropertyChanged)item).PropertyChanged += (s1, e1) => { if (setOK) enableOk = true; };
}
}
// handle collection changing
if (setOK) enableOk = false;
};
MyEntity me1 = new MyEntity { Name = "Name", Information = "Information", Details = "Detials" };
MyEntity me2 = new MyEntity { Name = "Name", Information = "Information", Details = "Detials" };
MyEntity me3 = new MyEntity { Name = "Name", Information = "Information", Details = "Detials" };
_entites.Add(me1);
_entites.Add(me2);
_entites.Add(me3);
// allow collection changes now to start enabling the ok button...
setOK = true;
RunCommand = new DelegateCommand<object>(OnRunCommnad, CanRunCommand);
OkCommand = new DelegateCommand<object>(OnOkCommnad, CanOkCommand);
}
private void OnRunCommnad(object obj)
{
MyEntity me = new MyEntity { Name = "Name", Information = "Information", Details = "Detials" };
// causes ok to become enabled
_entites.Add(me);
MyEntity first = _entites[0];
// causes ok to become enabled
first.Name = "Zamboni";
}
private bool CanRunCommand(object obj)
{
return true;
}
private void OnOkCommnad(object obj)
{
}
private bool CanOkCommand(object obj)
{
return enableOk;
}
}
这是MyEntity版本(类似于slugster提供的版本):
在此示例中,只有Name属性会触发事件...
public class MyEntity : INotifyPropertyChanged
{
private string _name = string.Empty;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public string Information { get; set; }
public string Details { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
关于c# - ObservableCollection,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3731941/