【问题标题】:Storing method from one class in a user control for later use将一个类中的方法存储在用户控件中以供以后使用
【发布时间】:2015-12-18 00:44:42
【问题描述】:

我想要的是将具有一个类拥有的参数的方法存储在另一个类的变量中以供以后执行。第一个类是我的 MainWindow 类,第二个是 UserControl。我要传递的方法将作为 UserControl 中包含的 ListBox 的 SelectionChanged 事件。该方法需要一个参数,只有在项目发生变化时 UserControl 才会知道。

我的方法(在 MainWindow 中)的示例如下:

public void MethodToPass(string UniqueParameterValue) {
    //...do stuff with special string
}

我会在我的 MainWindow 类中传递该方法,例如:

//In MainWindow.Loaded
this.userControlInstance.SelectionChanged += MethodToPass;

因为我没有直接将它分配给 ListBox,所以我会在 UserControl 中这样做:

private void selectionChanged;
public void SelectionChanged {
    get {
        ...
    } 
    set
    {
        this.selectionChanged = value;
        this.listBox1.SelectionChanged += value;
    }
}

我觉得不直接设置 ListBox 是多余的,但我的 MainWindow 类不允许我“看到”它。我也觉得这样做更政治正确的方法是将方法存储在变量中,但我不知道该怎么做或调用它。

这样的操作通常是怎么做的?

【问题讨论】:

  • 那么,您是否正试图根据用户控件中列表框上的事件调用主窗口类中的方法,其参数只有用户控件知道?我有这个权利吗?
  • 您可以利用 Action 和 Action,因为它们是代表。但似乎您对事件处理有一些误解。您能否分享更多代码并进一步阐明您要做什么?
  • @ScoobyDrew18 是的,MainWindow 包含一个名为 DocumentManager 的对象,它处理打开文件并根据打开的文件更改窗口 UI。 MethodToPass 中的字符串参数是我们要打开的文件的路径,属于 DocumentManager。 UserControl 将获取并返回一堆我们应该能够打开的文件,并在 ListBox 中选择文件时将文件路径传递给 MethodToPass。与其复制 DocumentManager 的 MethodToPass 方法并粘贴到 UserControl 中,我希望能够以某种方式从 UserControl 访问它,如果这有意义的话。

标签: c# wpf methods user-controls


【解决方案1】:

您应该能够像往常一样通过将它们创建为类属性来公开用户控件的属性。然后,您可以在您的用户控件上创建一个由 ListBox 的 SelectionChanged 事件引发的事件。您可以使用主窗口上的委托订阅此事件。

查看以下链接: How to access properties of a usercontrol in C#

How do I make an Event in the Usercontrol and Have it Handeled in the Main Form?

【讨论】:

  • 第二篇文章正是我需要的。谢谢!
猜你喜欢
  • 2020-04-20
  • 1970-01-01
  • 1970-01-01
  • 2014-02-03
  • 2011-10-21
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多