处理用户控件在其持有页面的代码后面的事件 [英] Handling event of user control in its holding page's code behind

查看:21
本文介绍了处理用户控件在其持有页面的代码后面的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为以下情况寻找解决方案.

I am looking for a solution for following situation.

在我的应用程序中,我有一个页面 page1,我在 page1 中放置了一个用户控件.我的要求是我需要在 page1 的代码后面获取用户控件中使用的按钮的单击事件.我如何在 windows 手机/silverlight 中实现相同的效果.

In my application i had a page say page1 and i placed a user control inside the page1. My requirement is i need to get the click event of button used in user control on page1's code behind. How i can achieve the same in windows phone / silverlight.

推荐答案

1.第一种也是正确的方式:

(如果您知道 MVVM 模式)将用于控制,例如 MyControl,以公开 ICommand 类型的 DependencyProperty,例如命名为MyControlButtonClickCommand.

1. The first and the right way:

(If you are aware of MVVM pattern) would be for you control, say MyControl, to expose DependencyProperty of type ICommand, named e.g. MyControlButtonClickCommand.

XML:

<UserControl>
    <Button Command={Binding MyControlButtonClickCommand, Source={RelativeSource Self}} />
</UserControl>  

代码隐藏:

public ICommand MyControlButtonClickCommand
{
    get { return (ICommand)GetValue(MyControlButtonClickCommandProperty); }
    set { SetValue(MyControlButtonClickCommandProperty, value); }
}

public static readonly DependencyProperty MyControlButtonClickCommandProperty =
        DependencyProperty.Register("MyControlButtonClickCommand", typeof(ICommand), typeof(MyControl), new PropertyMetadata(null));  

您可以按如下方式使用 UserControl:

You'd use you UserControl as follows:

<phone:PhoneApplicationPage>

    <namespace:MyControl MyControlButtonClickCommand="{Binding ControlButtonCommand}" />

</phone:PhoneApplicationPage>

其中 ControlButtonCommand 是 ViewModel(您的自定义对象)的一个属性,位于您的 Page 的 DataContext 中.

Where ControlButtonCommand is a property of a ViewModel (your custom object), living in a DataContext of your Page.

就像您公开 MyControlButtonClickCommand 依赖项属性一样,您可以公开一个事件 MyControlButtonClick 并在页面的 xaml 中订阅它,而不是公开它.在您的 UserControl 代码内部,您应该订阅它的按钮的 Click 事件并触发它自己的 MyControlButtonClick 事件.

Just like you expose MyControlButtonClickCommand dependency property and instead of exposing it, you can expose an event MyControlButtonClick and in the Page's xaml subscribe to it. Internally in your UserControl's code you should subscribe to it's button's Click event and fire its own MyControlButtonClick event.

希望对您有所帮助.

这篇关于处理用户控件在其持有页面的代码后面的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆