如何在主窗体中对UserControl中的Button点击事件进行更改? RRS feed

  • 问题

  • MainWindow下引用了一个UserControl命名为uc,uc中有个Button,如何在MainWindow中更改Button的点击事件,用以实现MainWindow的标题更改。
    2018年4月4日 7:35


  • Hi ShannonZhou,

    首先你需要改变在usercontrol中的button控件的fieldmodify属性为public, 然后改变button控件的事件胃public, 像这样:

    <StackPanel Width="80" Height="80">
            <Button x:Name="btn1" HorizontalAlignment="Center" x:FieldModifier="public" VerticalAlignment="Center"   Width="50" Content="click" Height="30" Click="btn1_Click"></Button>
     public partial class UserControl3 : UserControl
            public UserControl3()
            public void btn1_Click(object sender, RoutedEventArgs e)
                MessageBox.Show("usercontrol click event!");

    然后你就可以在主窗体中先remove掉button控件原有的事件, 然后在添加一个新的事件。

            <Button x:Name="btn1" Width="50" Height="30" Content="click" Click="btn1_Click"/>
            <Button x:Name="btn2" Width="50" Height="30" Content="click1" Click="btn2_Click"/>
            <local:UserControl3 x:Name="us" Margin="5" Width="100" Height="100" ></local:UserControl3>
      private void btn1_Click(object sender, RoutedEventArgs e)
                us.btn1.Click -= us.btn1_Click;
                us.btn1.Click += btn2_Click;
     private void btn2_Click(object sender, RoutedEventArgs e)
                MessageBox.Show("main windows click event");

    Best Regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    2018年4月5日 7:22