我正在尝试找出如何使用ViewModel
更新我的bool属性INotifyPropertyChanged
?
基本上在我的ViewModel中,我传入一个字符串列表。每个布尔属性都会检查列表以查看是否字符串值存在。
现在,在我的软件生命周期中,列表将得到更新,而我想更新每个属性使用INotifyPropertyChanged。
我的问题是如何从AddToList
方法调用INotifyPropertyChanged?正在为此使用一种方法正确的方向?
public class ViewModel : INotifyPropertyChanged
{
private List<string> _listOfStrings;
public ViewModel(List<string> ListOfStrings)
{
_listOfStrings = ListOfStrings;
}
public bool EnableProperty1 => _listOfStrings.Any(x => x == "Test1");
public bool EnableProperty2 => _listOfStrings.Any(x => x == "Test2");
public bool EnableProperty3 => _listOfStrings.Any(x => x == "Test3");
public bool EnableProperty4 => _listOfStrings.Any(x => x == "Test4");
public void AddToList(string value)
{
_listOfStrings.Add(financialProductType);
// Should I call the OnPropertyChanged here
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
最简单的操作是在OnPropertyChanged
方法中手动调用AddString
。
public void AddToList(string value)
{
_listOfStrings.Add(financialProductType);
OnPropertyChanged("EnableProperty1");
OnPropertyChanged("EnableProperty2");
// etc
}
如果您不太想改变班级,这很好。如果您添加根据_listOfStrings
计算出的另一个属性,则需要在此处添加OnPropertyChanged
调用。
使用ObservableCollection
并没有真正的帮助,因为您已经知道列表何时更改(AddToList
),并且仍然仍然必须触发所有OnPropertyChanged
方法。
据我所知,您在实现中缺少两件事:
ObservableCollection
而不是List
。顾名思义,前一个视图可以是observed
(通知其更改)。private ObservableCollection<string> _myList;
// your control should bind to this property
public ObservableCollection<string> MyList
{
get => return _myList;
set
{
// assign a new value to the list
_myList = value;
// notify view about the change
OnPropertiyChanged(nameof(MyList));
}
}
// some logic in your view model
string newValue = "newValue";
_myList.Add(newValue );
OnPropertyCHanged(nameof(MyList));
希望这有帮助吗?