在WinForm应用程序中的两个用户控件之间移动数据

时间:2011-03-19 16:03:30

标签: c# winforms

作为课程项目,我在c#中构建一个包含两个用户控件的表单。 第一个用户控件有一个checkedlistbox,当第一个控件checkedlistbox包含人员列表(男/女)时,第二个控件也有一个checkedlistbox,第二个用户控件checklistbox有两个选项:男性,女性和当我点击一个第一个控件上的按钮说:“更新朋友”它假设转到第二个控件并检查我们是否选择了男性或女性,并根据这个来更新第一个用户控件中的checkedlistbox与朋友按性别类型按选择的内容在第二个控制。

基本上我想在每次选择第一个控件上的按钮时引发一个事件,然后将数据从第二个控件传送到第一个控件。 是否可以在表单中的两个控件之间执行此操作并且是不同的控件?

任何帮助都会得到满足。 感谢。

2 个答案:

答案 0 :(得分:1)

要“正确”执行此操作,您可能希望使用类似MVC架构的内容。最初理解和实现的工作肯定要多得多,但知道你是否计划进行任何严肃的UI应用程序开发非常有用。即使你没有全力以赴,这些概念对于帮助设计“快速和肮脏”的应用程序也很有用。

定义您的数据模型,而不考虑用户界面,例如:

internal enum Gender
{
    Male,
    Female
}

internal class Person
{
    public Gender Gender { get; set; }

    public string Name { get; set; }
}

// . . .

// Populate the list of people
List<Person> allPeople = new List<Person>();
allPeople.Add(new Person() { Gender = Gender.Male, Name = "Xxx Yyy" });
allPeople.Add(new Person() { Gender = Gender.Female, Name = "Www Zzz" });

// . . .

对于视图部分,您通常会在UI控件上使用数据绑定,以便控件自动反映对基础数据的更改。但是,如果您不使用类似数据库的模型(例如System.Data.DataSet),这可能会变得困难。您可以选择“手动”更新控件中的数据,这可能适用于小型应用程序。

控制器是使用UI事件并对模型进行更改的部分,然后可以将其反映为视图中的更改。

internal class Controller
{
    private Gender selectedGender;
    private List<Person> allPeople;
    private List<Person> friends;

    public Controller(IEnumerable<Person> allPeople)
    {
        this.allPeople = new List<Person>(allPeople);
        this.friends = new List<Person>();
    }

    public void BindData(/* control here */)
    {
        // Code would go here to set up the data binding between
        // the friends list and the list box control
    }

    // Event subscriber for CheckedListBox.SelectedIndexChanged
    public void OnGenderSelected(object sender, EventArgs e)
    {
        CheckedListBox listBox = (CheckedListBox)sender;
        this.selectedGender = /* get selected gender from list box here */;
    }

    // Event subscriber for Button.Click
    public void OnUpdateFriends(object sender, EventArgs e)
    {
        this.friends.AddRange(
            from p in this.allPeople
            where p.Gender == this.selectedGender
            select p);
        // If you use data binding, you would need to ensure a
        // data update event is raised to inform the control
        // that it needs to update its view.
    }
}

// . . .

// On initialization, you'll need to set up the event handlers, etc.
updateFriendsButton.Click += controller.OnUpdateFriends;
genderCheckedListBox.SelectedIndexChanged += controller.OnGenderSelected;
controller.BindData(friendsListBox);

// . . .

基本上,我建议不要直接控制对话,而是通过类似控制器的类,如上所述,它具有数据模型和视图中其他控件的知识。

答案 1 :(得分:0)

当然有可能:您需要在表单中的两个控件之间建立链接。 只需在控件#1中声明一个事件'ButtonClicked' 然后在控件#2

上创建一个公共方法'PerformsClick'

在表单中,在构造函数中,在调用InitializeComponent之后,将控件#1中的事件链接到控件#2的方法:

control1.ButtonClicked += delegate(sender, e) {
  control2.PerformsClick();
};

(我在飞行中打字给你一个想法,肯定不会编译)

如果要传递任何数据,只需在PerformsClick方法中添加参数。