【发布时间】:2010-11-08 07:26:43
【问题描述】:
我有一个控件绑定到一个实现 INotifyPropertyChanged 的对象的索引属性。
问题是,我不知道如何通知该特定索引字符串的属性更改信号。
有人告诉我,我可以使用 OnPropertyChanged("") 来通知整个对象需要更改。
但我需要的是类似 OnPropertyChanged("Some index property string").
还有办法吗?
非常感谢。
ps:
我想要做的是应用 MVVM 模式。 我使用 viewmodel 类来包装一个普通的 POCO 对象。所以当我绑定时,我绑定到[索引属性],这样我就可以通知更改了。这种方法使我免于:
- 为我需要的每个属性包装内部域 POCO 对象。
- 通知每个包装属性中的属性已更改。
代码
public class ViewModelEx<T_Self, T_Core> : ViewModelEx<T_Self> where T_Self : ViewModelEx<T_Self, T_Core>
{
private static Type _s_coreType = typeof(T_Core);
private static Dictionary<string, PropertyInfo> _s_corePropInfos = new Dictionary<string, PropertyInfo>();
private static PropertyInfo GetPropertyInfo(string prop)
{
if (_s_corePropInfos.ContainsKey(prop) == false)
_s_corePropInfos.Add(prop, _s_coreType.GetProperty(prop));
return _s_corePropInfos[prop];
}
public T_Core Core { get; set; }
public object this[string propName]
{
get
{
return GetPropertyInfo(propName).GetValue(Core, null);
}
set
{
GetPropertyInfo(propName).SetValue(Core, value, null);
IsModified = true;
//RaisePropertyChanged(propName);
RaisePropertyChanged("");
}
}
public R Val<R>(Expression<Func<T_Core, R>> expr)
{
return (R)this[Core.GetPropertyStr(expr)];
}
public void Val<R>(Expression<Func<T_Core, R>> expr, R val)
{
this[Core.GetPropertyStr(expr)] = val;
}
【问题讨论】:
-
你的意思是this[string]还是this[int]?
-
我的意思是这个[字符串]。 this[string] 和 this[int] 之间的数据绑定/通知更改有什么区别?
-
我最终为每个域模型属性添加了属性包装器。事实证明,没有太多的工作。它避免了所有的问题。无论如何,这是一次性的努力。
标签: c# wpf data-binding mvvm indexer