我有2个部分类,Window A(frmSchedule)和Window B(frmAddLesson)。 Window A中有一个数据绑定的ListView控件。窗口A打开窗口B,用于创建一个新的Lesson对象,我想将该课程数据放回到窗口A中。有什么方法可以实现这一点?是否有一种在C#中使用应用程序范围变量的简单方法?
我尝试从单个基类派生两个部分类,并使用该类将Lesson数据汇集回第一个窗口,但我无法弄明白。 :(
有关详细信息,我已在此处列出了该计划:
我有一个主窗口(fmrSchedule),其中ListView控件绑定到ObservableCollection: (为简单起见,我假装Lesson对象只有1个重要的数据)
<ListView Name="lstLessons" Margin="204,15,192,125" ItemsSource="{Binding Path=LessonList}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Time}">Time</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
在代码中:
public partial class frmSchedule : Window
{
public frmSchedule()
{
InitializeComponent();
//ListView sample data
aLesson = new Lesson();
aLesson.Time = 9;
m_myLessons.Add(aLesson);
lstLessons.ItemsSource = LessonList;
}
Lesson aLesson;
private ObservableCollection<Lesson> m_myLessons = new ObservableCollection<Lesson>();
public ObservableCollection<Lesson> LessonList { get { return m_myLessons; } }
//Add Lesson
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
//New frmAddLesson window
frmAddLesson addLesson = new frmAddLesson();
addLesson.Show();
}
btnAdd按钮控件打开第二个表单(frmAddLesson),用于创建一个新的Lesson对象以添加到主窗口的Lesson列表中:(在这种情况下,时间是根据组合框选择设置的)< / p>
public partial class frmAddLesson : Window
{
public frmAddLesson(System.DateTime? DateTime)
{
InitializeComponent();
dateTime = DateTime;
radPrivate.IsChecked = true;
}
//DateTime from calendar selection
private DateTime? dateTime;
//Lesson object
private Lesson theLesson;
//ADD LESSON
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
//Create new Lesson object
theLesson = new Lesson();
//Set Lesson property
theLesson.Time = (int)cmbTime.SelectedValue; //Time
this.Close();
}
}
课程课程:
public class Lesson
{
public Lesson()
{
//Stuff for later
}
private int m_Time;
public int Time { get { return m_Time; } set { m_Time = value; } }
}
答案 0 :(得分:1)
public partial class frmSchedule : Window
{
...
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
//New frmAddLesson window
frmAddLesson addLesson = new frmAddLesson(this);
addLesson.Show();
}
public void AddLesson(Lesson lesson)
{
...
}
}
public partial class frmAddLesson : Window
{
public frmAddLesson(frmSchedule schedule)
{
InitializeComponent();
this.schedule = schedule;
...
}
frmSchedule schedule;
//ADD LESSON
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
//Create new Lesson object
var theLesson = new Lesson();
//Set Lesson property
theLesson.Time = (int)cmbTime.SelectedValue; //Time
schedule.AddLesson(theLesson);
this.Close();
}
}