gpt4 book ai didi

wpf - 在服务上实现 INotifyCollectionChanged 或 INotifyPropertyChanged 可以吗?

转载 作者:行者123 更新时间:2023-12-03 10:29:33 26 4
gpt4 key购买 nike

假设我有一个服务,它的接口(interface)是这样的:

public interface IProxyRotator
{
ProxyRotationMode RotationMode { get; set; }

void Add(Proxy proxy);
void AddRange(IEnumerable<Proxy> proxies);
bool Remove(Proxy proxy);
void Clear();
Proxy Peek();
}

问题在于我应该如何将服务中包含的代理绑定(bind)到 View 。

我正在做的方式是在服务接口(interface)上创建一个 ProxyList 数组并通知对该属性的更改。像这样:
public interface IProxyRotator : INotifyPropertyChanged
{
// ... omited for brevity
Proxy[] ProxyList { get; }
}

在 ViewModel 上,我有另一个用于代理的数组属性。当 ViewModel 被实例化时,它会订阅 IProxyRotator PropertyChanged 事件并“转发”该事件,以便 View 可以实际看到代理数组已更改。像这样:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel(IProxyRotator proxyRotator)
{
this.proxyRotator = proxyRotator;
this.proxyRotator.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == "ProxyList")
{
this.RaisePropertyChanged("ProxyList");
}
}
}

public Proxy[] ProxyList
{
get { return this.proxyRotator.ProxyList; }
}

private IProxyRotator proxyRotator;
}

问题是必须拦截服务 PropertyChanged 事件并转发它的开销让我感到困惑,感觉.. 错了。当我不得不依赖实现 INotifyPropertyChanged 的​​众多不同对象而不是正确实现 INotifyCollectionChanged 时,这也是一个主要缺点。
我是否应该考虑在 IProxyRotator 服务上实现 INotifyCollectionChanged(我知道这也意味着实现 IEnumerable)并简单地引用 ViewModel 上的服务,将 View 直接绑定(bind)到服务实例?

非常感谢您对此的评论!
谢谢!

最佳答案

INotifyCollectionChanged 将通知您(或 View )有关添加/删除的信息,但不会通知您(或 View )属性的更改(在更新的情况下)。 IPropertyChanged 可以通知 View 某个属性(对于实例 ProxyList)已更改(但不能通知此集合中项目的属性更改)。

此外,我认为您的服务不需要 INotifyCollectionChanged 接口(interface)。只需对 ProxyList 使用适当的实现,例如:

public interface IProxyRotator : INotifyPropertyChanged
{
// ... omited for brevity
ObservableCollection<Proxy> ProxyList { get; }
}

关于wpf - 在服务上实现 INotifyCollectionChanged 或 INotifyPropertyChanged 可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12083504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com