从用户控件中调用具有唯一参数的父级方法。

huangapple go评论63阅读模式
英文:

Call Method from User Control in Parent with Unique Parameters

问题

我有一个包含文本框和按钮的用户控件:

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

然后在我的主窗口中调用它:

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

btnBrowse_Click方法中,你可以这样调用ShowAMessage

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

请注意,在你的用户控件中,你已经声明了Code变量并创建了公共属性。

英文:

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

答案1

得分: 1

我试图重新创建相同的情况,代码应该可以正常工作,请尝试确保将Application.Current.MainWindow强制转换为正确的类型。

我唯一看到的问题是,如果你的UserControl的父窗口不是应用程序的启动窗口,那么可能会出现问题。

如果是这种情况,你可以使用Window.GetWindow(this),而不是使用Application.Current.MainWindow。这应该返回参数的父窗口。

关于属性的个人提示,如果你只是获取和设置后备字段,你可以这样写:
Public string Code { get; set; }
它应该能够完成相同的工作。

英文:

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:<br>
Public string Code { get; set; }<br>
It should do the same thing.

huangapple
  • 本文由 发表于 2023年5月15日 14:45:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76251474.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定