从方法更改属性以更新属性

问题描述 投票:0回答:2

我正在尝试找出如何使用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));
    }
}
c# viewmodel mvp inotifypropertychanged
2个回答
1
投票

最简单的操作是在OnPropertyChanged方法中手动调用AddString

public void AddToList(string value)
{
    _listOfStrings.Add(financialProductType);
    OnPropertyChanged("EnableProperty1");
    OnPropertyChanged("EnableProperty2");
    // etc
}

如果您不太想改变班级,这很好。如果您添加根据_listOfStrings计算出的另一个属性,则需要在此处添加OnPropertyChanged调用。

使用ObservableCollection并没有真正的帮助,因为您已经知道列表何时更改(AddToList),并且仍然仍然必须触发所有OnPropertyChanged方法。


1
投票

据我所知,您在实现中缺少两件事:

  1. 您应该使用ObservableCollection而不是List。顾名思义,前一个视图可以是observed(通知其更改)。
  2. 您需要将控件绑定到公共ObservableCollection,并在每次分配/更改集合的值时调用OnPropertyChanged。像这样的东西:
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));

希望这有帮助吗?

© www.soinside.com 2019 - 2024. All rights reserved.