[UWP]在父页面UWP中访问用户控件的按钮

人气:577 发布:2022-09-22 标签: wpdevelop

问题描述

我创建了一个名为UserControl的用户控件。

I have a user control created with name as UserControl.

此用户控件有一个标签和一个按钮。

This user control have a label and a button.

我在我的一个页面中使用此用户控件(比如说Page1),但是这个用户控件是根据DB中的条目生成的。例如:我在DB中有一个条目,其中有一个名为"UC1"的列。所以在页面(页面1)加载时,我在页面上动态添加此用户控件。

I use this user control in one of my page(lets say Page1), but this user control is generated based on the entries in DB. For eg: I have an entry in DB which has a column with name as 'UC1'. So on page(Page1) load, I dynamically add this usercontrol on the page.

现在加载页面时,我希望按钮单击方法在后面的Page1代码中实现。任何人都可以告诉我这是怎么可能的。我面临问题,因为使用控件是动态生成的,因为可以根据数据库条目在页面中生成多个usercontrols 实例。

Now when the page is loaded, I want the button click to method to be implemented in Page1 code behind. Could anyone let me know how is this possible. I am facing issue as the use control is dynamically generated and since multiple instances of usercontrols can be generated in the page based on the DB entries.

简而言之,我想在父页面后面的代码中调用一个方法,用于在父页面内动态生成的用户控件

In short I want to call a method in code behind of parent page for the user control that is dynamically generated inside the parent page

推荐答案

Hello Aswin M,

Hello Aswin M,

假设您的用户控件中的按钮具有名称"TheButton", ,

Supposing the button in your user control has the Name "TheButton",

<Button x:Name="TheButton" Content="Don't click"/>

定义一个自定义事件,使Button.Click可公开访问。

define a custom event to make the Button.Click publicly-accessible.

    public sealed partial class YourUserControl : UserControl
    {
        public event RoutedEventHandler ButtonClick
        {
            add { TheButton.Click += value; }
            remove { TheButton.Click -= value; }
        }

        public YourUserControl()
        {
            this.InitializeComponent(); //this.DataContext = this;
        }
    }

然后,您将能够在父页面中注册Click事件处理程序。

Then, you'll be able to register Click event handlerin the parent page.

            var control_instance = new YourUserControl();
            control_instance.ButtonClick += YourUserControl_ButtonClick;

193