我有一个 Windows 8.1 应用程序,其父视图模型和子视图模型具有以下关系
父视图模型
class ParentViewModel {
private double _parentAmount;
public double parentAmount
{
get { return _parentAmount; }
set
{
if (value != _parentAmount)
{
_parentAmount = value;
NotifyPropertyChanged("parentAmount");
}
}
}
private ObservableCollection<ChildViewModel> _children;
public ObservableCollection<ChildViewModel> children
{
get { return _children; }
set
{
if (value != _children)
{
_children = value;
NotifyPropertyChanged("children");
}
}
}
}
子视图模型
class ChildViewModel {
private double _ChildAmount;
public double ChildAmount
{
get { return _ChildAmount; }
set
{
if (value != _ChildAmount)
{
_ChildAmount = value;
NotifyPropertyChanged("ChildAmount");
}
}
}
}
在 XAML 中,有一个 TextBlock 绑定到“ParentAmount”,然后有一个 ListView 绑定到 Observable 集合“Children”。 ListView 的 Itemtemplate 是一个带有 TextBox 的数据模板,可以通过两种方式绑定到“ChildAmount”。用户可以修改子TextBox中的值
现在,我的要求是当用户修改子金额之一时,动态更新父金额及其所有子金额的总和。我该如何实现这一目标?
为了说明目的,我简化了上面粘贴的代码示例,ChildViewModel 具有比可见的功能更多的功能,因此我无法用 double 列表替换 ChildViewModel 的 ObservableCollection。
如果有人能指出我正确的方向,我将非常高兴。提前致谢。
只需添加很少的量,就可以达到目的。
具体的更改是为 ObservableCollection 中的每个子对象添加属性更改处理程序。
请注意,这是一个让您走上正确轨道的粗略示例 - 我还没有取消事件处理程序,并且我根据子项的任何更改重新计算父项金额(即,我不检查是否是 ChildAmount 发生了更改) ,这意味着您最终会采取比必要的更多的行动)。我也没有放入任何代码来处理 ObservableCollection 内容的更改,因此如果向其中添加新项目,它们将不会附加属性更改事件处理程序 - 这对您自己来说很简单。
请注意我对 BaseViewModel 的使用 - 这只是一个很好的实践,它使您无需在每个需要它的类上重新实现 INotifyPropertyChanged 接口。
class ParentViewModel : BaseViewModel
{
private double _parentAmount;
public double parentAmount
{
get { return _parentAmount; }
set
{
if (value != _parentAmount)
{
_parentAmount = value;
NotifyPropertyChanged("parentAmount");
}
}
}
private ObservableCollection<ChildViewModel> _children;
public ObservableCollection<ChildViewModel> children
{
get { return _children; }
set
{
if (value != _children)
{
_children = value;
foreach (var child in _children)
child.PropertyChanged += ChildOnPropertyChanged;
NotifyPropertyChanged("children");
}
}
}
private void ChildOnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
{
parentAmount = children.Sum(p => p.ChildAmount);
}
}
class ChildViewModel : BaseViewModel
{
private double _ChildAmount;
public double ChildAmount
{
get { return _ChildAmount; }
set
{
if (value != _ChildAmount)
{
_ChildAmount = value;
NotifyPropertyChanged("ChildAmount");
}
}
}
}
public class BaseViewModel : INotifyPropertyChanged
{
protected void NotifyPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)