绑定以计算可观察的子类集合

时间:2015-03-19 08:38:11

标签: c# wpf binding

我这里有一个WPF绑定问题。

安装后:

我有一个类(ActionService),它有一个名称和一个子项的ObservableCollection(也是一个名为Step的类)。步骤有一个标志,显示步骤是否已完成(IsDone)。

我将表单绑定到ActionService并显示所有类型的东西。

一切都按预期工作,我只有我的片段中的基本部分。

现在我还需要一件我无法工作的东西。我希望ActionService通过绑定知道其中有多少步骤是打开的(IsDone == false)。我用其中一个步骤打开一个子窗体并更改IsDone-State,母版本应该动态获得新的计数。

我在路上得到正确的解决方案是愚蠢的; - )

感谢您的帮助或最佳实践。



public class ActionService : BaseObject
{
	public ActionService()
	{
	}

	private String name;
	public String Name
	{
		get { return this.name; }
		set
		{
			this.name = value;
			raisePropertyChanged("Name");
		}
	}

	public ObservableCollection<Step> actionsteps;
	public ObservableCollection<Step> ActionSteps
	{
		get { return this.actionsteps; }
		set
		{
			this.actionsteps = value;
			raisePropertyChanged("ActionSteps");
		}
	}
	
}

public class Step : BaseObject
{
	public Step()
	{
	}
	
	private String description;
	public String Description
	{
		get { return this.description; }
		set
		{
			this.description = value;
			raisePropertyChanged("Description");
		}
	}
	
	private Boolean isdone;
	public Boolean IsDone
	{
		get { return this.isdone; }
		set
		{
			this.isdone = value;
			raisePropertyChanged("IsDone");
		}
	}
}

public class BaseObject : INotifyPropertyChanged
{
	public event PropertyChangedEventHandler PropertyChanged;
 
	protected void raisePropertyChanged(String parPropertyName)
	{
		if (this.PropertyChanged != null)
		{
			this.PropertyChanged(this, new PropertyChangedEventArgs(parPropertyName));
		}
	}
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以在ActionService课程中创建新媒体资源:

public bool IsDone
    {
        get 
        {
            return ActionSteps.Count(x => x.IsDone) == ActionSteps.Count;
        }
    }

如果ActionSteps列表中IsDone属性为true的步数等于ActionSteps列表中的步数,则返回true,否则返回false。

要订阅Steps属性更改事件,当您向集合中添加项目时,只需订阅 PropertyChanged 事件:

//Create the item and subscribe to propertychanged.
Step item = new Step();
item.PropertyChanged += item_PropertyChanged;

//Add the item to the list.
ActionSteps.Add(item);

您的方法将如下所示:

void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "IsDone")
            raisePropertyChanged("IsDone");
    }