Search code examples
c#wpfdata-binding

Call Method from User Control in Parent with Unique Parameters


I have a User Control that has a Textbox and a Button:

<TextBox Grid.Row="1" Text="SampleText" VerticalContentAlignment="Center"  />
<Button Name="btnBrowse" Click="btnBrowse_Click" Grid.Row="1" HorizontalAlignment="Right" Width="50" Content="..." />

I then call this on my Main Window:

<UserControls:MyTextbox Grid.Row="0" />

I have a method on my Main Window (parent):

public void ShowAMessage(string code)
{
    MessageBox.Show(code);
}

So now I wanna call the ShowAMessage on the parent from my UserControl, and it should pass a unique parameter called code. Is there some way to "declare" a unique code when importing the UserControl, that then I could pass to the ShowAMessage method?

I was thinking of something like this:

<UserControls:MyTextbox Grid.Row="0" Code="Hello There" />
<UserControls:MyTextbox Grid.Row="0" Code="Welcome" />

And then on the btnBrowse_Click:

((ParentWindow)Application.Current.MainWindow).ShowAMessage(Code);

But this doesn't work, gives me an InvalidCastException

Btw, I already declare the Code variable on the UserControl as well:

private string code;
public string Code
{
    get { return code; }
    set { code = value; }
}

Solution

  • I tried to recreate the same situation and the code should work, try to see if you're casting the Application.Current.MainWindow to the right type.

    The only problem I can see there is if the parent window of your UserControl is not the starting window of the application.

    If that's the case, instead of using Application.Current.MainWindow, you can use Window.GetWindow(this). That should return the parent window of the parameter.

    Personal tip for the property, if you just get and set the backing field, you can just write this:
    Public string Code { get; set; }
    It should do the same thing.