简体   繁体   English

MainWindow 中的按钮执行 UserControl1 中的方法

[英]Button in MainWindow executes method in UserControl1

I'm very new to programming and I cant seem to figure this out, reposting this with some more info.我对编程很陌生,我似乎无法弄清楚这一点,并重新发布了一些更多信息。 What I have is a MainWindow as well as a UserControl added into the MainWindow as a child.我所拥有的是一个 MainWindow 以及一个作为孩子添加到 MainWindow 中的 UserControl。 When I press a button in the MainWindow, I want it to call a method in the UserControl, this method is going to hide a grid.当我在 MainWindow 中按下一个按钮时,我希望它调用 UserControl 中的一个方法,该方法将隐藏一个网格。 This is what I have now...这就是我现在所拥有的...

//mainwindow
private void Button1_Click(object sender, RoutedEventArgs e)
{
    UserControl2 uc = new UserControl2();
    uc.MyMethod();
}


//usercontrol1
public void MyMethod()
{
    grid1.Visibility = Visibility.Hidden;
}

I have no errors showing, but it isn't hiding the grid.我没有显示错误,但它没有隐藏网格。

Disregarding the fact you should probably be using MVVM , you are nearly there.忽略您可能应该使用MVVM的事实,您就快到了。

MainWindow主窗口

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <local:UserControl2 x:Name="MyControl"></local:UserControl2>
    <Button Click="ButtonBase_OnClick" Width="100" Grid.Row="1">Click me</Button>
</Grid>

Code Behind代码背后

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
   MyControl.Method();
}

UserControl用户控制

<Grid x:Name="MyGrid">
       <Label> I want to hide</Label> 
</Grid>

Code Behind代码背后

public void Method()
{
    MyGrid.Visibility = Visibility.Hidden;
}

Before Click点击前

在此处输入图像描述

After Click点击后

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM