代表在Windows C#WPF之间传递数据

时间:2016-01-26 09:31:19

标签: c# wpf events delegates

我正在尝试使用Delegates在两个Windows之间传递数据。我想要在用户点击主People上的按钮时显示Window的列表,然后这将允许用户选择Person。完成此操作后,它将使用TextBox名称填写原始表单上的Person

我开始时比这简单得多,但要理解Delegates并且我在理解如何使用Windows在单独的Delegates上调用方法时遇到问题。这是我到目前为止所尝试的;

Window上等待string(ShowMessage)的方法;

public static DelegateTestWindow.TestDelegate ShowDelegateMessage(string message)
{
    MessageBox.Show(message);
    return null;
}

包含Window;

的第二个Delegate
public partial class DelegateTestWindow : Window
{
    public delegate string TestDelegate();
    public DelegateTestWindow()
    {
        InitializeComponent();
    }

    private void TestDelegateClick(object sender, RoutedEventArgs e)
    {
        var tDelegate = new TestDelegate(CompanyManagement.ShowDelegateMessage("Test"));
        this.Close();
    }
}

这确实会显示一条消息“测试”但是在执行此操作后它会抛出ExceptionDelegate to an instance method cannot have null 'this'.

MainWindow上的方法对我来说看起来不正确,但是在尝试了不同的选项后,这是我最接近工作Delegate的方法。有人可以解释我在这里(明显)出错的地方以及如何改进我现在所拥有的系统吗?

1 个答案:

答案 0 :(得分:1)

就像Mat链接一样,事件是一种特殊的委托,这可能就是你要找的东西。

我已经写了一个小例子,希望这足以让您解决问题。

.on('click touchstart', SECTION_NAV_SEL + ' a', sectionBulletHandler)

现在,这可以采用不同的方式,并且比这更好,但我认为这应该足够了。当你让它工作时,我建议你研究另一种方法。通常,您将创建一个继承自EventArgs的PersonEventArgs类。然后该班级持有对该人的引用。这是一个很好的链接示例: https://msdn.microsoft.com/en-us/library/system.eventargs(v=vs.110).aspx

祝你好运:)