WSkid
WSkid

Reputation: 2786

Call Function in Parent Window from Child Window

I'm attempting to implement a custom search dialog in a WPF program. The Parent window is a ListView that is bound to an Observable Collection.

I've made a new window with the search form and it is initialized like so:

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

and I have this function I am trying to call (in the Owner window):

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

Then in the Child window (searchForm) attempting to call selectIndex like so:

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);
        }

    }
}

I get the error: System.Windows.Window does not contain a definition for "selectIndex".

The _QPCollection is the observable collection that the search will loop through. I have the search logic working, but I cannot seem Focus() the index of the ListView in the Parent Window.

My first thought was to have a public function that I could pass the index to and it would do the focus, but I cannot seem to find a way to call function from the Child Window that are in the Parent Window.

Am I approaching this completely wrong? This answer seems to be for WinForms but I am sure there is a way to access the Parent Window and its public functions/properties in WPF.

Upvotes: 2

Views: 12601

Answers (2)

brunnerh
brunnerh

Reputation: 185290

If you set the Owner like you did, you should be able to call public methods inside the dialogue via (Owner as MyWindowDerivative).Method() (if Owner is of type Window), what exactly is stopping you from doing that?

Edit: If you are going to go that route you should make sure that Owner is always of type MyWindowDerivative, e.g. by overwriting the Owner-Property, also prevent parameterless constructors.

Upvotes: 4

Jacob
Jacob

Reputation: 78910

A cleaner way of handling that scenario would be for your searchForm to raise an event. The parent window could listen for that event and set the focus on its own list view:

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;

Upvotes: 7

Related Questions