我遇到了与此问题相同的问题:TextBox, Button and ListBox in a ListBox
所以我接受了@Andy的回答,但它给了我麻烦:
private void ButtonAddNewTask_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
IssueView curIssue = (Issue)btn.DataContext;
if (curIssue != null)
{
curIssue.Issue.Comments.Add(new Comment()
{
Commentary = curIssue.NewCommentName
});
}
}
我想知道这是不是我的错误,如果帖子太旧或@Andy遗忘了什么而且我无法得到什么,我也没有很好地适应我的代码。
修改我的课程和改编的按钮点击事件
public sealed class Issue
{
public string Name { get; set; }
public string Detail { get; set; }
private ObservableCollection<Comment> comments =
new ObservableCollection<Comment>();
public IList<Comment> Comments
{
get { return comments; }
}
}
public sealed class Comment
{
// string AssociatedIssue { get; set; }
public string Commentary { get; set; }
}
class IssueView : INotifyPropertyChanged
{
public Issue Issue { get; set; }
private string newCommentName = string.Empty;
public string NewCommentName
{
get { return newCommentName; }
set
{
newCommentName = value;
OnPropertyChanged("NewCommentName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
}
答案 0 :(得分:0)
// Types at the beginning and end of this statement should be the same
ProjectView curProject = btn.DataContext as ProjectView;
答案 1 :(得分:0)
您需要在ProjectView变量(而不是Project)中存储ProjectView。
ProjectView curProject = (btn.DataContext as ProjectView);
如果DataContext永远不能转换为ProjectView,那么curProject将始终为null。
答案 2 :(得分:-2)
你能这样试试吗?:
private void ButtonAddNewTask_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
ProjectView curProject = (Project) btn.DataContext;
if(null != curProject)
{
curProject.Project.Tasks.Add(new Task()
{
Name = curProject.NewTaskName
});
}
}
您是如何尝试将项目转换为ProjectView的?看来,它们是两个不同的类,没有任何继承。