【问题标题】:Call Function in Parent Window from Child Window从子窗口调用父窗口中的函数
【发布时间】:2011-11-12 21:10:09
【问题描述】:

我正在尝试在 WPF 程序中实现自定义搜索对话框。 Parent 窗口是一个绑定到 Observable Collection 的 ListView。

我用搜索表单创建了一个新窗口,它的初始化如下:

searchForm sf = new searchForm(_QPCollection);
sf.Owner = this;
sf.Show();

我有这个函数我正在尝试调用(在所有者窗口中):

public void selectIndex(int index)
{
    ListViewItem toSelect = listView1.Items[index] as ListViewItem;
    toSelect.Focus();
}

然后在子窗口 (searchForm) 中尝试像这样调用 selectIndex:

public void SearchJob_Click(object sender, RoutedEventArgs e)
{
    if (sJob.Text == "" || sJob.Text == null) { return; }
    for (int i = findCount; i < _QPCollectionSearch.Count; i++)
    {
        if (i == _QPCollectionSearch.Count - 1) { i = 0; }
        if (_QPCollectionSearch[i].jobNumAndFlow.IndexOf(sJob.Text) > -1)
        {
            findCount = i;
            Owner.selectIndex(i);
        }

    }
}

我收到错误:System.Windows.Window 不包含“selectIndex”的定义。

_QPCollection 是搜索将循环遍历的可观察集合。我的搜索逻辑正常工作,但我无法在父窗口中看到 Focus() ListView 的索引。

我的第一个想法是有一个公共函数,我可以将索引传递给它并获得焦点,但我似乎找不到从父窗口中的子窗口调用函数的方法。

我的做法完全错误吗?这个answer 似乎适用于 WinForms,但我确信有一种方法可以访问 WPF 中的父窗口及其公共功能/属性。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    处理这种情况的一种更简洁的方法是让您的searchForm 引发事件。父窗口可以监听该事件并将焦点设置在它自己的列表视图上:

    public class searchForm 
    {
        public event EventHandler<SearchEventArgs> SearchResultSelected = delegate { };
    }
    
    public class SearchEventArgs : EventArgs
    {
        public int Index { get; set; }
    }
    
    searchForm sf = new searchForm(_QPCollection);
    sf.SearchResultSelected += (s, e) => MyListView.SelectedIndex = e.Index;
    

    【讨论】:

      【解决方案2】:

      如果你像你一样设置Owner,你应该可以通过(Owner as MyWindowDerivative).Method()调用对话中的公共方法(如果所有者是Window类型),究竟是什么阻止你这样做?

      编辑:如果你要走那条路,你应该确保Owner 始终是MyWindowDerivative 类型,例如通过覆盖 Owner-Property,还可以防止无参数构造函数。

      【讨论】:

      • 我添加了更多代码,并引发了错误消息——它没有 Method() 的定义。
      • 问题在于 searchForm 依赖于 MyWindowDerivative,并且 searchForm 不能由不同类型的窗口生成。如果您不关心这一点,那么此解决方案可以正常工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      相关资源
      最近更新 更多